diff --git a/app/web/components/CartoonNextAction.tsx b/app/web/components/CartoonNextAction.tsx new file mode 100644 index 0000000..19ea48f --- /dev/null +++ b/app/web/components/CartoonNextAction.tsx @@ -0,0 +1,145 @@ +import { useEffect, useState } from "react"; +import type { StoryProgress } from "@app-lib/story-progress"; +import type { CoachUiAction } from "@app-lib/cartoon-coach"; +import { WorkflowCoachView } from "./WorkflowCoach"; + +export function storyInfoNextStep(progress: StoryProgress): string { + if (progress.cover !== "present") { + return progress.cover === "invalid" + ? "Replace the cover image - it must be a valid WebP or JPEG." + : "Add a cover image before publishing."; + } + const missing: string[] = []; + if (!progress.metadata.language) missing.push("language"); + if (!progress.metadata.genre) missing.push("genre"); + if (!progress.metadata.title) missing.push("title"); + return `Add the story ${missing.join(" and ") || "details"} before publishing.`; +} + +export function cartoonWorkflowActiveKey(progress: StoryProgress): string | null { + const coach = progress.coach ?? null; + const m = progress.metadata; + const hasStructure = progress.setup.hasStructure; + const hasGenesis = progress.setup.hasGenesis; + const coverDone = progress.cover === "present"; + const metadataIncomplete = !m.title || !m.language || !m.genre; + const activeEp = progress.episodes.find((e) => !e.published) ?? null; + const productionPending = !!activeEp && activeEp.state !== "ready"; + + if (!hasStructure) return "whitepaper"; + if (!hasGenesis) return "genesis.md"; + if (metadataIncomplete) return "story-info"; + if (productionPending && coach?.episodeFile) return coach.episodeFile; + if (!coverDone) return "story-info"; + return coach?.episodeFile ?? null; +} + +export function StoryInfoNextActionCard({ + progress, + onOpenStoryInfo, +}: { + progress: StoryProgress; + onOpenStoryInfo?: () => void; +}) { + return ( +
+
+
+ + Story info + +

+ Next: + {storyInfoNextStep(progress)} +

+
+ +
+
+ ); +} + +export function CartoonNextActionView({ + progress, + onCoachAction, + onOpenStoryInfo, +}: { + progress: StoryProgress; + onCoachAction: (action: CoachUiAction, episodeFile: string | null) => void; + onOpenStoryInfo?: () => void; +}) { + const activeKey = cartoonWorkflowActiveKey(progress); + if (activeKey === "story-info") { + return ; + } + return ( + + ); +} + +export function CartoonNextAction({ + storyName, + authFetch, + refreshKey = 0, + onCoachAction, + onOpenStoryInfo, +}: { + storyName: string; + authFetch: (url: string, opts?: RequestInit) => Promise; + refreshKey?: number; + onCoachAction: (action: CoachUiAction, episodeFile: string | null) => void; + onOpenStoryInfo?: () => void; +}) { + const [progress, setProgress] = useState(undefined); + + const targetKey = JSON.stringify([storyName, refreshKey]); + const [loadedKey, setLoadedKey] = useState(null); + if (loadedKey !== targetKey) { + setProgress(undefined); + setLoadedKey(targetKey); + } + + useEffect(() => { + let cancelled = false; + authFetch(`/api/stories/${storyName}/progress`) + .then((res) => (res.ok ? res.json() : null)) + .then((data: StoryProgress | null) => { + if (!cancelled) setProgress(isValidProgress(data) ? data : null); + }) + .catch(() => { + if (!cancelled) setProgress(null); + }); + return () => { cancelled = true; }; + }, [storyName, authFetch, refreshKey]); + + if (progress === undefined) return null; + if (!progress) { + return ; + } + return ( + + ); +} + +function isValidProgress(data: StoryProgress | null): data is StoryProgress { + return !!data + && !!data.metadata + && !!data.setup + && Array.isArray(data.episodes); +} diff --git a/app/web/components/PreviewPanel.test.tsx b/app/web/components/PreviewPanel.test.tsx index 3eae5fc..9059d6a 100644 --- a/app/web/components/PreviewPanel.test.tsx +++ b/app/web/components/PreviewPanel.test.tsx @@ -57,7 +57,8 @@ describe("PreviewPanel — Genesis workflow-coach cut actions (#429)", () => { // The coach loads for Genesis with an in-app (lettering) action. const doBtn = await screen.findByTestId("workflow-coach-do"); - expect(doBtn).toHaveTextContent(/lettering/i); + expect(screen.getByTestId("workflow-coach-action")).toHaveTextContent(/Review cuts and start lettering/i); + expect(doBtn).toHaveTextContent("Next Action"); // Before acting, the cut workspace isn't mounted. expect(screen.queryByTestId("cut-list-panel")).not.toBeInTheDocument(); diff --git a/app/web/components/PreviewPanel.tsx b/app/web/components/PreviewPanel.tsx index 36ee5dc..2d7a7ac 100644 --- a/app/web/components/PreviewPanel.tsx +++ b/app/web/components/PreviewPanel.tsx @@ -1015,6 +1015,7 @@ export function PreviewPanel({ storyName, fileName, authFetch, onPublish, publis authFetch={authFetch} refreshKey={cutsRefreshKey} onAction={handleCoachAction} + showEmptyState /> )} diff --git a/app/web/components/StoriesPage.test.tsx b/app/web/components/StoriesPage.test.tsx index 1676ab2..67b0de9 100644 --- a/app/web/components/StoriesPage.test.tsx +++ b/app/web/components/StoriesPage.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, vi, afterEach, beforeAll } from "vitest"; -import { render, screen, cleanup, waitFor, fireEvent } from "@testing-library/react"; +import { render, screen, cleanup, waitFor, fireEvent, within } from "@testing-library/react"; import { StoriesPage } from "./StoriesPage"; // Capture props passed to the mocked child panels so tests can drive the @@ -428,13 +428,37 @@ function makeTwoCartoonAuthFetch() { { name: "cartoon-a", title: "Story A", hasStructure: true, hasGenesis: true, contentType: "cartoon", agentProvider: "codex" }, { name: "cartoon-b", title: "Story B", hasStructure: true, hasGenesis: true, contentType: "cartoon", agentProvider: "codex" }, ]; + const progress = { + name: "cartoon-a", + contentType: "cartoon", + metadata: { title: "Story A", language: "English", genre: "Science Fiction", isNsfw: false, contentType: "cartoon" }, + setup: { hasStructure: true, hasGenesis: true }, + cover: "missing", + episodes: [ + { + file: "genesis.md", + label: "Episode 1 / Genesis", + kind: "genesis", + title: "Opening", + state: "ready", + summary: "Ready to publish", + published: false, + checklist: [], + cuts: { total: 0, needClean: 0, withClean: 0, withText: 0, exported: 0, uploaded: 0 }, + }, + ], + summary: { episodes: 1, published: 0, readyToPublish: 1, placeholders: 0, blocked: 0 }, + nextAction: "Add a cover image before publishing.", + nextPrompt: null, + coach: null, + }; const fn = vi.fn().mockImplementation((url: string, opts?: RequestInit) => { if (url === "/api/wallet") return Promise.resolve({ ok: true, json: () => Promise.resolve({ address: "0xabc" }) }); if (url === "/api/agent/readiness") { return Promise.resolve({ ok: true, json: () => Promise.resolve({ claude: { installed: true }, codex: { installed: true, version: "codex-cli 0.135.0", imageGeneration: "enabled", auth: "ok" }, checkedAt: 1748000000000 }) }); } if (url === "/api/stories" && !opts) return Promise.resolve({ ok: true, json: () => Promise.resolve({ stories }) }); - if (url.endsWith("/progress")) return Promise.resolve({ ok: true, json: () => Promise.resolve({ contentType: "cartoon", episodes: [], cover: "missing" }) }); + if (url.endsWith("/progress")) return Promise.resolve({ ok: true, json: () => Promise.resolve(progress) }); // story detail (cartoon ⇒ no auto-open) and everything else. return Promise.resolve({ ok: true, json: () => Promise.resolve({ contentType: "cartoon", files: [] }) }); }); @@ -487,4 +511,24 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { expect(screen.getByTestId("nav-tab-genesis")).toHaveAttribute("data-active", "false"); expect(screen.queryByTestId("mock-preview")).not.toBeInTheDocument(); }, 10000); + + it("shows the Story Info next-action CTA on story-level right-pane pages when cover is missing (#487 RE1)", async () => { + const { fn } = makeTwoCartoonAuthFetch(); + render(); + await waitFor(() => expect(childProps.onSelectStory).not.toBeNull()); + childProps.onSelectStory!("cartoon-a"); + + fireEvent.click(await screen.findByTestId("nav-tab-publish")); + const publishCta = await screen.findByTestId("workflow-context-next-action"); + expect(within(publishCta).getByTestId("story-info-next-action")).toHaveTextContent(/Next: Add a cover image before publishing/i); + expect(within(publishCta).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); + expect(within(publishCta).queryByText("No next action available")).not.toBeInTheDocument(); + + fireEvent.click(within(publishCta).getByRole("button", { name: "Next Action" })); + await waitFor(() => expect(screen.getByTestId("nav-tab-story-info")).toHaveAttribute("data-active", "true")); + + const storyInfoCta = screen.getByTestId("workflow-context-next-action"); + expect(within(storyInfoCta).getByTestId("story-info-next-action")).toHaveTextContent(/Next: Add a cover image before publishing/i); + expect(within(storyInfoCta).queryByText("No next action available")).not.toBeInTheDocument(); + }, 10000); }); diff --git a/app/web/components/StoriesPage.tsx b/app/web/components/StoriesPage.tsx index e45e0b1..b8d45d3 100644 --- a/app/web/components/StoriesPage.tsx +++ b/app/web/components/StoriesPage.tsx @@ -7,11 +7,13 @@ import { CartoonWorkflowNav, type CartoonWorkflowTab } from "./CartoonWorkflowNa import { StoryInfoPage } from "./StoryInfoPage"; import { EpisodesPage } from "./EpisodesPage"; import { CartoonPublishPage } from "./CartoonPublishPage"; +import { CartoonNextAction } from "./CartoonNextAction"; import { LANGUAGES, GENRES } from "../../../lib/genres"; import { getContentTypeForPublish, resolveSelectedContentType, needsLegacyProviderRepair, attachCoverToStoryline, derivePublishTitle, shouldBlockDuplicatePlotPublish, isRawFilenameTitle, hasExplicitEpisodeTitle, isPreflightBlocked, formatPreflightBlock } from "../lib/publish-helpers"; import { verifyPublicCartoonTitle, publicTitleWarning } from "../lib/verify-public-title"; import { isCodexAuthUnclear, CODEX_AUTH_UNCLEAR_MESSAGE, type AgentReadiness } from "@app-lib/agent-readiness"; import { cartoonGenesisReadiness } from "@app-lib/cartoon-readiness"; +import type { CoachUiAction } from "@app-lib/cartoon-coach"; interface StoriesPageProps { token: string; @@ -763,6 +765,27 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { } }, [selectedStory, handleSelectFile]); + const handleWorkflowNextAction = useCallback((action: CoachUiAction, episodeFile: string | null) => { + const story = selectedStory; + if (!story) return; + switch (action) { + case "view-progress": + setCartoonView(null); + setSelectedFile(null); + break; + case "publish": + setCartoonView("publish"); + break; + case "open-cuts": + case "open-lettering": + case "upload": + case "refresh-assets": + case "generate-markdown": + if (episodeFile) handleSelectFile(story, episodeFile); + break; + } + }, [selectedStory, handleSelectFile]); + // Keep the publish-control seeds in sync after a Story Info save (#439). const handleStoryInfoSaved = useCallback((patch: { genre?: string; language?: string; isNsfw?: boolean }) => { if (!selectedStory) return; @@ -814,6 +837,17 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { onSelect={handleCartoonNav} /> )} + {isCartoonStory && selectedStory && cartoonView !== null && ( +
+ setCartoonView("story-info")} + /> +
+ )} {isCartoonStory && cartoonView === "story-info" && selectedStory ? ( ) : isCartoonStory && cartoonView === "episodes" && selectedStory ? ( @@ -836,6 +870,7 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { storyName={selectedStory} authFetch={authFetch} onOpenFile={handleSelectFile} + onOpenStoryInfo={() => setCartoonView("story-info")} /> ) : ( { expect(screen.getByTestId("workflow-section-4")).toHaveTextContent("Episode 2"); }); - it("places exactly one next-action CTA, inside the active (current) episode section", async () => { + it("places exactly one prominent persistent next-action CTA above the workflow map", async () => { render(); await screen.findByTestId("story-progress-panel"); - // Only one CTA on the whole page (no duplicated global coach bar). - expect(screen.getAllByTestId("section-cta")).toHaveLength(1); - expect(screen.getAllByTestId("workflow-coach")).toHaveLength(1); + const nextAction = screen.getByTestId("persistent-next-action"); + expect(within(nextAction).getAllByTestId("workflow-coach")).toHaveLength(1); + expect(screen.queryByTestId("section-cta")).toBeNull(); - // The active step is Genesis (coach targets genesis.md, cover present) → the - // CTA lives in section 3, not in Story Info / Whitepaper / Episode 2. + // The active step is Genesis (coach targets genesis.md, cover present), but + // the CTA is now persistent above the map rather than embedded in section 3. const genesisSection = screen.getByTestId("workflow-section-3"); - expect(within(genesisSection).getByTestId("workflow-coach")).toHaveTextContent(/Publish/); expect(genesisSection).toHaveAttribute("data-status", "current"); - expect(within(screen.getByTestId("workflow-section-1")).queryByTestId("section-cta")).toBeNull(); - expect(within(screen.getByTestId("workflow-section-4")).queryByTestId("section-cta")).toBeNull(); + + expect(within(nextAction).getByTestId("workflow-coach-action")).toHaveTextContent("Next: Publish Episode 1 / Genesis to PlotLink"); + expect(within(nextAction).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); + expect(within(nextAction).queryByRole("button", { name: /Publish Episode 1/i })).toBeNull(); }); it("clicking the active CTA routes to the episode it concerns", async () => { @@ -172,19 +173,25 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { // #444 RE1: when Story Info (cover/metadata) is incomplete and Genesis is // otherwise ready, the single CTA must be in Define Story Info, not Genesis. it("puts the single CTA in Story Info when the cover is missing (not in the ready Genesis)", async () => { - render(); + const onOpenStoryInfo = vi.fn(); + render(); await screen.findByTestId("story-progress-panel"); - expect(screen.getAllByTestId("section-cta")).toHaveLength(1); + expect(screen.queryByTestId("section-cta")).toBeNull(); + const nextAction = screen.getByTestId("persistent-next-action"); + expect(within(nextAction).getByTestId("story-info-cta")).toBeInTheDocument(); + expect(within(nextAction).getByTestId("story-info-next-action")).toHaveTextContent(/Next: Add a cover image/i); + const button = within(nextAction).getByRole("button", { name: "Next Action" }); + expect(button).toBeEnabled(); + fireEvent.click(button); + expect(onOpenStoryInfo).toHaveBeenCalledTimes(1); + const info = screen.getByTestId("workflow-section-1"); expect(info).toHaveAttribute("data-status", "current"); - expect(within(info).getByTestId("section-cta")).toHaveTextContent(/cover image/i); - expect(within(info).getByTestId("story-info-cta")).toBeInTheDocument(); expect(within(info).getByText(/Missing/)).toBeInTheDocument(); - // The ready Genesis must NOT hold the CTA, nor read as the current step. + // The ready Genesis must not read as the current step. const genesis = screen.getByTestId("workflow-section-3"); - expect(within(genesis).queryByTestId("section-cta")).toBeNull(); expect(genesis).not.toHaveAttribute("data-status", "current"); }); @@ -194,17 +201,19 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { render(); await screen.findByTestId("story-progress-panel"); - // Exactly one CTA, and it lives in the Genesis (Episode 1) section. - expect(screen.getAllByTestId("section-cta")).toHaveLength(1); + const nextAction = screen.getByTestId("persistent-next-action"); + expect(screen.queryByTestId("section-cta")).toBeNull(); + expect(within(nextAction).getByTestId("workflow-coach-action")).toHaveTextContent(/Next: Review cuts and start lettering/i); + expect(within(nextAction).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); + + // Genesis (Episode 1) remains the current workflow section. const genesis = screen.getByTestId("workflow-section-3"); expect(genesis).toHaveAttribute("data-status", "current"); - expect(within(genesis).getByTestId("section-cta")).toHaveTextContent(/Review cuts and start lettering/i); // Story Info is NOT the current step — the missing cover reads as a // recommendation (needs-action), and the cover stays visible as "Missing". const info = screen.getByTestId("workflow-section-1"); expect(info).not.toHaveAttribute("data-status", "current"); - expect(within(info).queryByTestId("section-cta")).toBeNull(); expect(within(info).getByText(/Missing/)).toBeInTheDocument(); // The cover CTA / "add a cover" wording must not appear anywhere. expect(screen.queryByTestId("story-info-cta")).toBeNull(); @@ -217,13 +226,16 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { render(); await screen.findByTestId("story-progress-panel"); - expect(screen.getAllByTestId("section-cta")).toHaveLength(1); + const nextAction = screen.getByTestId("persistent-next-action"); + expect(screen.queryByTestId("section-cta")).toBeNull(); + expect(within(nextAction).getByTestId("workflow-coach")).toHaveTextContent(/Write the Genesis/i); + expect(within(nextAction).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); + // Whitepaper is complete; the Genesis (Episode 1) section is the current step. expect(screen.getByTestId("workflow-section-2")).toHaveAttribute("data-status", "done"); const genesis = screen.getByTestId("workflow-section-3"); expect(genesis).toHaveTextContent("Episode 1 / Genesis"); expect(genesis).toHaveAttribute("data-status", "current"); - expect(within(genesis).getByTestId("workflow-coach")).toHaveTextContent(/Write the Genesis/i); }); it("shows a friendly error if progress cannot be loaded", async () => { diff --git a/app/web/components/StoryProgressPanel.tsx b/app/web/components/StoryProgressPanel.tsx index 9c0c98e..33ca610 100644 --- a/app/web/components/StoryProgressPanel.tsx +++ b/app/web/components/StoryProgressPanel.tsx @@ -1,13 +1,15 @@ -import { useEffect, useState, type ReactNode } from "react"; +import { useEffect, useState } from "react"; import type { StoryProgress, EpisodeProgress, EpisodeState } from "@app-lib/story-progress"; import type { CartoonChecklistStep } from "@app-lib/cartoon-readiness"; -import { WorkflowCoachView } from "./WorkflowCoach"; +import { cartoonWorkflowActiveKey, CartoonNextActionView } from "./CartoonNextAction"; interface StoryProgressPanelProps { storyName: string; authFetch: (url: string, opts?: RequestInit) => Promise; /** Open a file from the map (the workflow steps link to their file). */ onOpenFile: (storyName: string, file: string) => void; + /** Open the Story Info workflow page when metadata/cover is the next gate. */ + onOpenStoryInfo?: () => void; /** Bumped by the parent to force a refresh (e.g. after a publish). */ refreshKey?: number; } @@ -18,15 +20,13 @@ interface StoryProgressPanelProps { * For CARTOON stories this is the writer's main production dashboard: a vertical * workflow map of numbered sections (Define Story Info → Story Whitepaper → * Genesis / Episode 1 → Episode 2 …), each with a checkbox checklist and a clear - * status. The single next-action CTA is rendered inside the section it belongs to - * (never a duplicated global bar), so a first-time creator understands the whole - * webtoon workflow and where they are in it without reading terminal output or - * raw file names. + * status. The single next-action CTA stays persistent above the map, while the + * current section still marks where that action belongs. * * FICTION keeps the simpler original layout — metadata, setup steps, a chapter * list — and is completely unaffected by the cartoon redesign. */ -export function StoryProgressPanel({ storyName, authFetch, onOpenFile, refreshKey = 0 }: StoryProgressPanelProps) { +export function StoryProgressPanel({ storyName, authFetch, onOpenFile, onOpenStoryInfo, refreshKey = 0 }: StoryProgressPanelProps) { const [progress, setProgress] = useState(null); const [loading, setLoading] = useState(true); @@ -56,7 +56,7 @@ export function StoryProgressPanel({ storyName, authFetch, onOpenFile, refreshKe } return progress.contentType === "cartoon" - ? + ? : ; } @@ -128,13 +128,11 @@ function ChecklistRow({ item }: { item: ChecklistItem }) { } /** - * One numbered workflow section: a status bullet + title + status badge, a nested - * checklist, and — only for the active section — the single next-action CTA. The - * header navigates to `openFile` when one is provided (sections whose dedicated - * page does not exist yet, e.g. Story Info, render a plain header). + * One numbered workflow section: a status bullet + title + status badge, plus a + * nested checklist. The header navigates to `openFile` when one is provided. */ function Section({ - index, title, status, items, fileName, openFile, cta, + index, title, status, items, fileName, openFile, }: { index: number; title: string; @@ -144,8 +142,6 @@ function Section({ fileName?: string | null; /** Called to open the section's underlying file, or undefined for no navigation. */ openFile?: () => void; - /** The single CTA node, rendered under this section when it is the active one. */ - cta?: ReactNode; }) { const heading = (
@@ -163,7 +159,6 @@ function Section({
{items.map((it, i) => )}
- {cta &&
{cta}
}
); } @@ -207,89 +202,32 @@ const GENESIS_STUB: EpisodeProgress = { state: "placeholder", summary: "", published: false, checklist: [], cuts: null, }; -/** The single Story-Info next step, when cover/metadata is the active gate. */ -function storyInfoNextStep(progress: StoryProgress): string { - if (progress.cover !== "present") { - return progress.cover === "invalid" - ? "Replace the cover image — it must be a valid WebP or JPEG." - : "Add a cover image before publishing."; - } - const missing: string[] = []; - if (!progress.metadata.language) missing.push("language"); - if (!progress.metadata.genre) missing.push("genre"); - if (!progress.metadata.title) missing.push("title"); - return `Add the story ${missing.join(" and ") || "details"} before publishing.`; -} - function CartoonWorkflowMap({ - progress, storyName, onOpenFile, -}: { progress: StoryProgress; storyName: string; onOpenFile: (storyName: string, file: string) => void }) { - const coach = progress.coach ?? null; + progress, storyName, onOpenFile, onOpenStoryInfo, +}: { + progress: StoryProgress; + storyName: string; + onOpenFile: (storyName: string, file: string) => void; + onOpenStoryInfo?: () => void; +}) { const m = progress.metadata; const hasStructure = progress.setup.hasStructure; - const hasGenesis = progress.setup.hasGenesis; const coverDone = progress.cover === "present"; - // Required publish metadata (title/language/genre) still hard-gates the active - // step. A missing COVER is a publish-readiness recommendation, NOT the primary - // step (#462) — it's kept out of the active-gate decision while an episode is - // mid-production, so the cut/lettering production CTA leads instead. const metadataIncomplete = !m.title || !m.language || !m.genre; const storyInfoIncomplete = metadataIncomplete || !coverDone; - // The active (first unpublished) episode and whether it still has production - // work to do (anything short of publish-ready). - const activeEp = progress.episodes.find((e) => !e.published) ?? null; - const productionPending = !!activeEp && activeEp.state !== "ready"; - - // The SINGLE active gate, chosen in the same order buildStoryProgress derives - // its next step (structure → genesis → story info/cover → active episode), so - // the one CTA always matches the story-level next action and lands in its own - // section. `deriveCartoonCoach` agrees on every gate EXCEPT story info (it - // skips cover/metadata), so we own that gate here; the coach drives the rest. - // Crucially, every gate maps to a section that is ALWAYS rendered (Whitepaper, - // the always-present Genesis section, an episode, or the trailing block), so - // the CTA can never fall through the cracks (#444 review: it vanished when the - // bible was written but Genesis wasn't). - let activeKey: string | null; - if (!hasStructure) activeKey = "whitepaper"; - else if (!hasGenesis) activeKey = "genesis.md"; - else if (metadataIncomplete) activeKey = "story-info"; - // #462: a mid-production episode leads over a missing cover — the cut/lettering - // production CTA is the primary step. A missing cover only becomes the active - // step once the active episode's production is complete (no work pending), - // where it reads as the publish-readiness recommendation. - else if (productionPending && coach?.episodeFile) activeKey = coach.episodeFile; - else if (!coverDone) activeKey = "story-info"; - else activeKey = coach?.episodeFile ?? null; - - // The coach-driven CTA (setup prompts + episode actions), reused from the - // tested coach view so routing stays byte-identical to the old overview. - const coachCta = coach ? ( - { + const activeKey = cartoonWorkflowActiveKey(progress); + + const topNextAction = ( + { if (action === "view-progress") return; // already here if (episodeFile) onOpenFile(storyName, episodeFile); }} /> - ) : null; - - // Story Info owns the CTA when metadata/cover is the gate. There is no - // dedicated Story Info page yet (#439/§4) and the coach carries no cover - // action, so this is an informational next-step line (not a route) — still the - // one and only CTA, placed in the relevant section. - const storyInfoCta = ( -
- Story info - Next: {storyInfoNextStep(progress)} -
); - // Return the one CTA for a section, or null — guarantees a single visible CTA. - const ctaFor = (key: string): ReactNode => { - if (key !== activeKey) return null; - return activeKey === "story-info" ? storyInfoCta : coachCta; - }; - const infoItems: ChecklistItem[] = [ { label: "Public title", status: m.title ? "done" : "todo", detail: m.title ?? null }, { label: "Language", status: m.language ? "done" : "todo", detail: m.language ?? null }, @@ -307,6 +245,9 @@ function CartoonWorkflowMap({ return (
+
+ {topNextAction} +

Production Progress

onOpenFile(storyName, "structure.md") : undefined} items={[{ label: "Planning document", status: hasStructure ? "done" : "todo", detail: hasStructure ? null : "Not written yet" }]} - cta={ctaFor("whitepaper") ?? undefined} /> {/* Genesis / Episode 1 — always shown (a not-started stub before it's @@ -332,29 +271,22 @@ function CartoonWorkflowMap({ {genesisEp ? ( ) : ( )} {plotEps.map((ep) => ( ))} - {/* All episodes published with nothing queued → a trailing "start next" CTA. */} - {activeKey === null && coachCta && ( -
-
{coachCta}
-
- )} -
{progress.summary.published} published {progress.summary.readyToPublish} ready @@ -367,14 +299,13 @@ function CartoonWorkflowMap({ /** A `progress-episode-` section, kept testid-stable so clicking it opens the file. */ function EpisodeSection({ - index, ep, isActive, storyName, onOpenFile, cta, openingDone = true, canOpen = true, + index, ep, isActive, storyName, onOpenFile, openingDone = true, canOpen = true, }: { index: number; ep: EpisodeProgress; isActive: boolean; storyName: string; onOpenFile: (storyName: string, file: string) => void; - cta?: ReactNode; /** Whether the genesis opening text is already written (false for the stub). */ openingDone?: boolean; /** Whether the header navigates to the file (false for the not-yet-written stub). */ @@ -408,7 +339,6 @@ function EpisodeSection({
{items.map((it, i) => )}
- {cta &&
{cta}
}
); } diff --git a/app/web/components/WorkflowCoach.test.tsx b/app/web/components/WorkflowCoach.test.tsx index e1d1f20..6913ceb 100644 --- a/app/web/components/WorkflowCoach.test.tsx +++ b/app/web/components/WorkflowCoach.test.tsx @@ -32,6 +32,12 @@ describe("WorkflowCoachView (#429)", () => { expect(container.firstChild).toBeNull(); }); + it("can render a clear completed state when there is no queued coach", () => { + render(); + expect(screen.getByTestId("workflow-coach")).toHaveAttribute("data-state", "complete"); + expect(screen.getByText("No next action available")).toBeInTheDocument(); + }); + it("agent step: shows the action and copies the prompt", () => { const writeText = vi.fn().mockResolvedValue(undefined); Object.assign(navigator, { clipboard: { writeText } }); diff --git a/app/web/components/WorkflowCoach.tsx b/app/web/components/WorkflowCoach.tsx index eb0d772..e17d490 100644 --- a/app/web/components/WorkflowCoach.tsx +++ b/app/web/components/WorkflowCoach.tsx @@ -24,53 +24,80 @@ interface WorkflowCoachViewProps { /** Run an app-driven step (the agent steps copy a prompt instead). */ onAction: (action: CoachUiAction, episodeFile: string | null) => void; className?: string; + /** Show a clear completed state instead of disappearing when no coach exists. */ + showEmptyState?: boolean; } -export function WorkflowCoachView({ coach, onAction, className = "" }: WorkflowCoachViewProps) { +export function WorkflowCoachView({ coach, onAction, className = "", showEmptyState = false }: WorkflowCoachViewProps) { // Track the prompt that was copied rather than a bare boolean, so the "Copied!" // confirmation derives to false the moment the coach (and its prompt) changes — // no reset effect, no stale confirmation under a new stage. const [copiedPrompt, setCopiedPrompt] = useState(null); const copied = copiedPrompt !== null && copiedPrompt === coach?.prompt; - if (!coach) return null; + if (coach === undefined) return null; + if (!coach) { + if (!showEmptyState) return null; + return ( +
+
+ + Complete + +
+

No next action available

+

This workflow has no queued next step right now.

+
+
+
+ ); + } return (
- - {coach.stageLabel} - - - Next: - {coach.action} - - {coach.actionKind === "agent" && coach.prompt ? ( - - ) : coach.actionKind === "ui" && coach.uiAction ? ( - - ) : null} +
+
+ + {coach.stageLabel} + +

+ Next: + {coach.action} +

+ {copied &&

Prompt copied.

} +
+ {coach.actionKind === "agent" && coach.prompt ? ( + + ) : coach.actionKind === "ui" && coach.uiAction ? ( + + ) : null} +
); } @@ -83,6 +110,7 @@ interface WorkflowCoachProps { /** Bumped by the parent to reload after a state change (cut edit / publish). */ refreshKey?: number; onAction: (action: CoachUiAction, episodeFile: string | null) => void; + showEmptyState?: boolean; } /** @@ -92,8 +120,8 @@ interface WorkflowCoachProps { * previous file's coach can never linger under a different file when the new * request fails or 404s (the stale-state-on-error class flagged on #420/#427). */ -export function WorkflowCoach({ storyName, fileName, authFetch, refreshKey = 0, onAction }: WorkflowCoachProps) { - const [coach, setCoach] = useState(null); +export function WorkflowCoach({ storyName, fileName, authFetch, refreshKey = 0, onAction, showEmptyState = false }: WorkflowCoachProps) { + const [coach, setCoach] = useState(undefined); // Reset the coach the instant the target changes (file switch / refresh), // during render — React's recommended way to reset state on a changing input. @@ -108,7 +136,7 @@ export function WorkflowCoach({ storyName, fileName, authFetch, refreshKey = 0, const targetKey = JSON.stringify([storyName, fileName ?? "", refreshKey]); const [loadedKey, setLoadedKey] = useState(null); if (loadedKey !== targetKey) { - setCoach(null); + setCoach(undefined); setLoadedKey(targetKey); } @@ -124,5 +152,5 @@ export function WorkflowCoach({ storyName, fileName, authFetch, refreshKey = 0, return () => { cancelled = true; }; }, [storyName, fileName, authFetch, refreshKey]); - return ; + return ; } diff --git a/app/web/dist/assets/export-cut-DRQwImdk.js b/app/web/dist/assets/export-cut-DAQ_YjPc.js similarity index 98% rename from app/web/dist/assets/export-cut-DRQwImdk.js rename to app/web/dist/assets/export-cut-DAQ_YjPc.js index 351a259..a8d1517 100644 --- a/app/web/dist/assets/export-cut-DRQwImdk.js +++ b/app/web/dist/assets/export-cut-DAQ_YjPc.js @@ -1 +1 @@ -import{M as w,v as O,t as A,c as M,b as R,s as H,l as I,a as B,d as F}from"./index-CyiSY_SY.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; +import{M as w,v as O,t as A,c as M,b as R,s as H,l as I,a as B,d as F}from"./index-B066-0l8.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; diff --git a/app/web/dist/assets/index-CyiSY_SY.js b/app/web/dist/assets/index-B066-0l8.js similarity index 60% rename from app/web/dist/assets/index-CyiSY_SY.js rename to app/web/dist/assets/index-B066-0l8.js index ae0cf04..acf3c0f 100644 --- a/app/web/dist/assets/index-CyiSY_SY.js +++ b/app/web/dist/assets/index-B066-0l8.js @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Vx;function Qw(){if(Vx)return to;Vx=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return to.Fragment=t,to.jsx=i,to.jsxs=i,to}var Xx;function Jw(){return Xx||(Xx=1,qd.exports=Qw()),qd.exports}var f=Jw(),Wd={exports:{}},et={};/** + */var X_;function eC(){if(X_)return to;X_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return to.Fragment=t,to.jsx=i,to.jsxs=i,to}var Z_;function tC(){return Z_||(Z_=1,qd.exports=eC()),qd.exports}var f=tC(),Wd={exports:{}},et={};/** * @license React * react.production.js * @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Zx;function eC(){if(Zx)return et;Zx=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),_=Symbol.for("react.activity"),b=Symbol.iterator;function v(R){return R===null||typeof R!="object"?null:(R=b&&R[b]||R["@@iterator"],typeof R=="function"?R:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,A={};function N(R,Y,C){this.props=R,this.context=Y,this.refs=A,this.updater=C||y}N.prototype.isReactComponent={},N.prototype.setState=function(R,Y){if(typeof R!="object"&&typeof R!="function"&&R!=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,R,Y,"setState")},N.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function L(){}L.prototype=N.prototype;function O(R,Y,C){this.props=R,this.context=Y,this.refs=A,this.updater=C||y}var J=O.prototype=new L;J.constructor=O,E(J,N.prototype),J.isPureReactComponent=!0;var $=Array.isArray;function M(){}var X={H:null,A:null,T:null,S:null},he=Object.prototype.hasOwnProperty;function ye(R,Y,C){var ae=C.ref;return{$$typeof:e,type:R,key:Y,ref:ae!==void 0?ae:null,props:C}}function U(R,Y){return ye(R.type,Y,R.props)}function se(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function W(R){var Y={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(C){return Y[C]})}var G=/\/+/g;function Z(R,Y){return typeof R=="object"&&R!==null&&R.key!=null?W(""+R.key):Y.toString(36)}function I(R){switch(R.status){case"fulfilled":return R.value;case"rejected":throw R.reason;default:switch(typeof R.status=="string"?R.then(M,M):(R.status="pending",R.then(function(Y){R.status==="pending"&&(R.status="fulfilled",R.value=Y)},function(Y){R.status==="pending"&&(R.status="rejected",R.reason=Y)})),R.status){case"fulfilled":return R.value;case"rejected":throw R.reason}}throw R}function j(R,Y,C,ae,ie){var oe=typeof R;(oe==="undefined"||oe==="boolean")&&(R=null);var F=!1;if(R===null)F=!0;else switch(oe){case"bigint":case"string":case"number":F=!0;break;case"object":switch(R.$$typeof){case e:case t:F=!0;break;case x:return F=R._init,j(F(R._payload),Y,C,ae,ie)}}if(F)return ie=ie(R),F=ae===""?"."+Z(R,0):ae,$(ie)?(C="",F!=null&&(C=F.replace(G,"$&/")+"/"),j(ie,Y,C,"",function(De){return De})):ie!=null&&(se(ie)&&(ie=U(ie,C+(ie.key==null||R&&R.key===ie.key?"":(""+ie.key).replace(G,"$&/")+"/")+F)),Y.push(ie)),1;F=0;var ue=ae===""?".":ae+":";if($(R))for(var be=0;be>>1,T=j[_e];if(0>>1;_ea(C,B))aea(ie,C)?(j[_e]=ie,j[ae]=B,_e=ae):(j[_e]=C,j[Y]=B,_e=Y);else if(aea(ie,B))j[_e]=ie,j[ae]=B,_e=ae;else break e}}return z}function a(j,z){var B=j.sortIndex-z.sortIndex;return B!==0?B:j.id-z.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 c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],d=[],x=1,_=null,b=3,v=!1,y=!1,E=!1,A=!1,N=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function J(j){for(var z=i(d);z!==null;){if(z.callback===null)s(d);else if(z.startTime<=j)s(d),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(d)}}function $(j){if(E=!1,J(j),!y)if(i(p)!==null)y=!0,M||(M=!0,W());else{var z=i(d);z!==null&&I($,z.startTime-j)}}var M=!1,X=-1,he=5,ye=-1;function U(){return A?!0:!(e.unstable_now()-yej&&U());){var _e=_.callback;if(typeof _e=="function"){_.callback=null,b=_.priorityLevel;var T=_e(_.expirationTime<=j);if(j=e.unstable_now(),typeof T=="function"){_.callback=T,J(j),z=!0;break t}_===i(p)&&s(p),J(j)}else s(p);_=i(p)}if(_!==null)z=!0;else{var R=i(d);R!==null&&I($,R.startTime-j),z=!1}}break e}finally{_=null,b=B,v=!1}z=void 0}}finally{z?W():M=!1}}}var W;if(typeof O=="function")W=function(){O(se)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,Z=G.port2;G.port1.onmessage=se,W=function(){Z.postMessage(null)}}else W=function(){N(se,0)};function I(j,z){X=N(function(){j(e.unstable_now())},z)}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(j){j.callback=null},e.unstable_forceFrameRate=function(j){0>j||125_e?(j.sortIndex=B,t(d,j),i(p)===null&&j===i(d)&&(E?(L(X),X=-1):E=!0,I($,B-_e))):(j.sortIndex=T,t(p,j),y||v||(y=!0,M||(M=!0,W()))),j},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(j){var z=b;return function(){var B=b;b=z;try{return j.apply(this,arguments)}finally{b=B}}}})(Kd)),Kd}var eb;function nC(){return eb||(eb=1,Yd.exports=iC()),Yd.exports}var Vd={exports:{}},Xi={};/** + */var eb;function rC(){return eb||(eb=1,(function(e){function t(j,O){var B=j.length;j.push(O);e:for(;0>>1,T=j[xe];if(0>>1;xea(C,B))sea(te,C)?(j[xe]=te,j[se]=B,xe=se):(j[xe]=C,j[Y]=B,xe=Y);else if(sea(te,B))j[xe]=te,j[se]=B,xe=se;else break e}}return O}function a(j,O){var B=j.sortIndex-O.sortIndex;return B!==0?B:j.id-O.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 c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],d=[],_=1,x=null,b=3,v=!1,y=!1,N=!1,A=!1,E=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function J(j){for(var O=i(d);O!==null;){if(O.callback===null)s(d);else if(O.startTime<=j)s(d),O.sortIndex=O.expirationTime,t(p,O);else break;O=i(d)}}function q(j){if(N=!1,J(j),!y)if(i(p)!==null)y=!0,L||(L=!0,W());else{var O=i(d);O!==null&&I(q,O.startTime-j)}}var L=!1,Z=-1,he=5,ye=-1;function U(){return A?!0:!(e.unstable_now()-yej&&U());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var T=xe(x.expirationTime<=j);if(j=e.unstable_now(),typeof T=="function"){x.callback=T,J(j),O=!0;break t}x===i(p)&&s(p),J(j)}else s(p);x=i(p)}if(x!==null)O=!0;else{var R=i(d);R!==null&&I(q,R.startTime-j),O=!1}}break e}finally{x=null,b=B,v=!1}O=void 0}}finally{O?W():L=!1}}}var W;if(typeof P=="function")W=function(){P(re)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,X=G.port2;G.port1.onmessage=re,W=function(){X.postMessage(null)}}else W=function(){E(re,0)};function I(j,O){Z=E(function(){j(e.unstable_now())},O)}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(j){j.callback=null},e.unstable_forceFrameRate=function(j){0>j||125xe?(j.sortIndex=B,t(d,j),i(p)===null&&j===i(d)&&(N?(D(Z),Z=-1):N=!0,I(q,B-xe))):(j.sortIndex=T,t(p,j),y||v||(y=!0,L||(L=!0,W()))),j},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(j){var O=b;return function(){var B=b;b=O;try{return j.apply(this,arguments)}finally{b=B}}}})(Kd)),Kd}var tb;function sC(){return tb||(tb=1,Yd.exports=rC()),Yd.exports}var Vd={exports:{}},Ji={};/** * @license React * react-dom.production.js * @@ -30,7 +30,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var tb;function rC(){if(tb)return Xi;tb=1;var e=Op();function t(p){var d="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vd.exports=rC(),Vd.exports}/** + */var ib;function aC(){if(ib)return Ji;ib=1;var e=Op();function t(p){var d="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vd.exports=aC(),Vd.exports}/** * @license React * react-dom-client.production.js * @@ -38,15 +38,15 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var nb;function aC(){if(nb)return io;nb=1;var e=nC(),t=Op(),i=sC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=_e[T],_e[T]=null,T--)}function C(n,r){T++,_e[T]=n.current,n.current=r}var ae=R(null),ie=R(null),oe=R(null),F=R(null);function ue(n,r){switch(C(oe,r),C(ie,n),C(ae,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?xx(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=xx(r),n=bx(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}Y(ae),C(ae,n)}function be(){Y(ae),Y(ie),Y(oe)}function De(n){n.memoizedState!==null&&C(F,n);var r=ae.current,l=bx(r,n.type);r!==l&&(C(ie,n),C(ae,l))}function Ee(n){ie.current===n&&(Y(ae),Y(ie)),F.current===n&&(Y(F),Zl._currentValue=B)}var Be,je;function Ze(n){if(Be===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Be=r&&r[1]||"",je=-1T||(n.current=xe[T],xe[T]=null,T--)}function C(n,r){T++,xe[T]=n.current,n.current=r}var se=R(null),te=R(null),oe=R(null),$=R(null);function ue(n,r){switch(C(oe,r),C(te,n),C(se,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?b_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=b_(r),n=v_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}Y(se),C(se,n)}function be(){Y(se),Y(te),Y(oe)}function De(n){n.memoizedState!==null&&C($,n);var r=se.current,l=v_(r,n.type);r!==l&&(C(te,n),C(se,l))}function Ee(n){te.current===n&&(Y(se),Y(te)),$.current===n&&(Y($),Zl._currentValue=B)}var Be,je;function Ze(n){if(Be===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Be=r&&r[1]||"",je=-1)":-1m||D[u]!==V[m]){var le=` -`+D[u].replace(" at new "," at ");return n.displayName&&le.includes("")&&(le=le.replace("",n.displayName)),le}while(1<=u&&0<=m);break}}}finally{we=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ze(l):""}function mt(n,r){switch(n.tag){case 26:case 27:case 5:return Ze(n.type);case 16:return Ze("Lazy");case 13:return n.child!==r&&r!==null?Ze("Suspense Fallback"):Ze("Suspense");case 19:return Ze("SuspenseList");case 0:case 15:return tt(n.type,!1);case 11:return tt(n.type.render,!1);case 1:return tt(n.type,!0);case 31:return Ze("Activity");default:return""}}function Ge(n){try{var r="",l=null;do r+=mt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`);for(m=u=0;um||M[u]!==V[m]){var le=` +`+M[u].replace(" at new "," at ");return n.displayName&&le.includes("")&&(le=le.replace("",n.displayName)),le}while(1<=u&&0<=m);break}}}finally{Ce=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ze(l):""}function pt(n,r){switch(n.tag){case 26:case 27:case 5:return Ze(n.type);case 16:return Ze("Lazy");case 13:return n.child!==r&&r!==null?Ze("Suspense Fallback"):Ze("Suspense");case 19:return Ze("SuspenseList");case 0:case 15:return tt(n.type,!1);case 11:return tt(n.type.render,!1);case 1:return tt(n.type,!0);case 31:return Ze("Activity");default:return""}}function Ge(n){try{var r="",l=null;do r+=pt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Ae=Object.prototype.hasOwnProperty,Ve=e.unstable_scheduleCallback,Mt=e.unstable_cancelCallback,zt=e.unstable_shouldYield,ai=e.unstable_requestPaint,wt=e.unstable_now,hi=e.unstable_getCurrentPriorityLevel,re=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,Pe=e.unstable_NormalPriority,Fe=e.unstable_LowPriority,Qe=e.unstable_IdlePriority,H=e.log,ge=e.unstable_setDisableYieldValue,Te=null,me=null;function He(n){if(typeof H=="function"&&ge(n),me&&typeof me.setStrictMode=="function")try{me.setStrictMode(Te,n)}catch{}}var Oe=Math.clz32?Math.clz32:Dt,ut=Math.log,it=Math.LN2;function Dt(n){return n>>>=0,n===0?32:31-(ut(n)/it|0)|0}var Bt=256,di=262144,kt=4194304;function Ci(n){var r=n&42;if(r!==0)return r;switch(n&-n){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 n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function fi(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,S=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ci(u):(S&=k,S!==0?m=Ci(S):l||(l=k&~n,l!==0&&(m=Ci(l))))):(k=u&~g,k!==0?m=Ci(k):S!==0?m=Ci(S):l||(l=u&~n,l!==0&&(m=Ci(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function Gt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function fn(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+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 r+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 de(){var n=kt;return kt<<=1,(kt&62914560)===0&&(kt=4194304),n}function Re(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function We(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function st(n,r,l,u,m,g){var S=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,D=n.expirationTimes,V=n.hiddenUpdates;for(l=S&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var fa=/[\n"\\]/g;function ki(n){return n.replace(fa,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function pa(n,r,l,u,m,g,S,k){n.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?n.type=S:n.removeAttribute("type"),r!=null?S==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+kn(r)):n.value!==""+kn(r)&&(n.value=""+kn(r)):S!=="submit"&&S!=="reset"||n.removeAttribute("value"),r!=null?ga(n,S,kn(r)):l!=null?ga(n,S,kn(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+kn(k):n.removeAttribute("name")}function ma(n,r,l,u,m,g,S,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){sr(n);return}l=l!=null?""+kn(l):"",r=r!=null?""+kn(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(n.name=S),sr(n)}function ga(n,r,l){r==="number"&&rn(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function $n(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),gi=!1;if(Nt)try{var En={};Object.defineProperty(En,"passive",{get:function(){gi=!0}}),window.addEventListener("test",En,En),window.removeEventListener("test",En,En)}catch{gi=!1}var an=null,lr=null,Ls=null;function bm(){if(Ls)return Ls;var n,r=lr,l=r.length,u,m="value"in an?an.value:an.textContent,g=m.length;for(n=0;n=xl),km=" ",Em=!1;function Nm(n,r){switch(n){case"keyup":return v1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Tm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var va=!1;function S1(n,r){switch(n){case"compositionend":return Tm(r);case"keypress":return r.which!==32?null:(Em=!0,km);case"textInput":return n=r.data,n===km&&Em?null:n;default:return null}}function w1(n,r){if(va)return n==="compositionend"||!Xu&&Nm(n,r)?(n=bm(),Ls=lr=an=null,va=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Om(l)}}function Pm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Pm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Im(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=rn(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=rn(n.document)}return r}function Ju(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var R1=Nt&&"documentMode"in document&&11>=document.documentMode,ya=null,eh=null,Sl=null,th=!1;function Hm(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;th||ya==null||ya!==rn(u)||(u=ya,"selectionStart"in u&&Ju(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Sl&&yl(Sl,u)||(Sl=u,u=Dc(eh,"onSelect"),0>=S,m-=S,mr=1<<32-Oe(r)+m|l<at?(yt=Ie,Ie=null):yt=Ie.sibling;var At=Q(q,Ie,K[at],ce);if(At===null){Ie===null&&(Ie=yt);break}n&&Ie&&At.alternate===null&&r(q,Ie),P=g(At,P,at),jt===null?Ue=At:jt.sibling=At,jt=At,Ie=yt}if(at===K.length)return l(q,Ie),St&&Dr(q,at),Ue;if(Ie===null){for(;atat?(yt=Ie,Ie=null):yt=Ie.sibling;var Cs=Q(q,Ie,At.value,ce);if(Cs===null){Ie===null&&(Ie=yt);break}n&&Ie&&Cs.alternate===null&&r(q,Ie),P=g(Cs,P,at),jt===null?Ue=Cs:jt.sibling=Cs,jt=Cs,Ie=yt}if(At.done)return l(q,Ie),St&&Dr(q,at),Ue;if(Ie===null){for(;!At.done;at++,At=K.next())At=fe(q,At.value,ce),At!==null&&(P=g(At,P,at),jt===null?Ue=At:jt.sibling=At,jt=At);return St&&Dr(q,at),Ue}for(Ie=u(Ie);!At.done;at++,At=K.next())At=ne(Ie,q,at,At.value,ce),At!==null&&(n&&At.alternate!==null&&Ie.delete(At.key===null?at:At.key),P=g(At,P,at),jt===null?Ue=At:jt.sibling=At,jt=At);return n&&Ie.forEach(function(Zw){return r(q,Zw)}),St&&Dr(q,at),Ue}function Ht(q,P,K,ce){if(typeof K=="object"&&K!==null&&K.type===E&&K.key===null&&(K=K.props.children),typeof K=="object"&&K!==null){switch(K.$$typeof){case v:e:{for(var Ue=K.key;P!==null;){if(P.key===Ue){if(Ue=K.type,Ue===E){if(P.tag===7){l(q,P.sibling),ce=m(P,K.props.children),ce.return=q,q=ce;break e}}else if(P.elementType===Ue||typeof Ue=="object"&&Ue!==null&&Ue.$$typeof===he&&Ws(Ue)===P.type){l(q,P.sibling),ce=m(P,K.props),Tl(ce,K),ce.return=q,q=ce;break e}l(q,P);break}else r(q,P);P=P.sibling}K.type===E?(ce=Hs(K.props.children,q.mode,ce,K.key),ce.return=q,q=ce):(ce=Xo(K.type,K.key,K.props,null,q.mode,ce),Tl(ce,K),ce.return=q,q=ce)}return S(q);case y:e:{for(Ue=K.key;P!==null;){if(P.key===Ue)if(P.tag===4&&P.stateNode.containerInfo===K.containerInfo&&P.stateNode.implementation===K.implementation){l(q,P.sibling),ce=m(P,K.children||[]),ce.return=q,q=ce;break e}else{l(q,P);break}else r(q,P);P=P.sibling}ce=oh(K,q.mode,ce),ce.return=q,q=ce}return S(q);case he:return K=Ws(K),Ht(q,P,K,ce)}if(I(K))return ze(q,P,K,ce);if(W(K)){if(Ue=W(K),typeof Ue!="function")throw Error(s(150));return K=Ue.call(K),qe(q,P,K,ce)}if(typeof K.then=="function")return Ht(q,P,nc(K),ce);if(K.$$typeof===O)return Ht(q,P,Jo(q,K),ce);rc(q,K)}return typeof K=="string"&&K!==""||typeof K=="number"||typeof K=="bigint"?(K=""+K,P!==null&&P.tag===6?(l(q,P.sibling),ce=m(P,K),ce.return=q,q=ce):(l(q,P),ce=lh(K,q.mode,ce),ce.return=q,q=ce),S(q)):l(q,P)}return function(q,P,K,ce){try{Nl=0;var Ue=Ht(q,P,K,ce);return Ma=null,Ue}catch(Ie){if(Ie===Ra||Ie===tc)throw Ie;var jt=Tn(29,Ie,null,q.mode);return jt.lanes=ce,jt.return=q,jt}finally{}}}var Ys=cg(!0),ug=cg(!1),ls=!1;function vh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function yh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function os(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function cs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Rt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=Vo(n),Ym(n,null,l),r}return Ko(n,u,r,l),Vo(n)}function jl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,te(n,l)}}function Sh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=S:g=g.next=S,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var wh=!1;function Al(){if(wh){var n=Aa;if(n!==null)throw n}}function Rl(n,r,l,u){wh=!1;var m=n.updateQueue;ls=!1;var g=m.firstBaseUpdate,S=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var D=k,V=D.next;D.next=null,S===null?g=V:S.next=V,S=D;var le=n.alternate;le!==null&&(le=le.updateQueue,k=le.lastBaseUpdate,k!==S&&(k===null?le.firstBaseUpdate=V:k.next=V,le.lastBaseUpdate=D))}if(g!==null){var fe=m.baseState;S=0,le=V=D=null,k=g;do{var Q=k.lane&-536870913,ne=Q!==k.lane;if(ne?(vt&Q)===Q:(u&Q)===Q){Q!==0&&Q===ja&&(wh=!0),le!==null&&(le=le.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var ze=n,qe=k;Q=r;var Ht=l;switch(qe.tag){case 1:if(ze=qe.payload,typeof ze=="function"){fe=ze.call(Ht,fe,Q);break e}fe=ze;break e;case 3:ze.flags=ze.flags&-65537|128;case 0:if(ze=qe.payload,Q=typeof ze=="function"?ze.call(Ht,fe,Q):ze,Q==null)break e;fe=_({},fe,Q);break e;case 2:ls=!0}}Q=k.callback,Q!==null&&(n.flags|=64,ne&&(n.flags|=8192),ne=m.callbacks,ne===null?m.callbacks=[Q]:ne.push(Q))}else ne={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},le===null?(V=le=ne,D=fe):le=le.next=ne,S|=Q;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ne=k,k=ne.next,ne.next=null,m.lastBaseUpdate=ne,m.shared.pending=null}}while(!0);le===null&&(D=fe),m.baseState=D,m.firstBaseUpdate=V,m.lastBaseUpdate=le,g===null&&(m.shared.lanes=0),ps|=S,n.lanes=S,n.memoizedState=fe}}function hg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function dg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var S=j.T,k={};j.T=k,$h(n,!1,r,l);try{var D=m(),V=j.S;if(V!==null&&V(k,D),D!==null&&typeof D=="object"&&typeof D.then=="function"){var le=H1(D,u);Bl(n,r,le,Dn(n))}else Bl(n,r,u,Dn(n))}catch(fe){Bl(n,r,{then:function(){},status:"rejected",reason:fe},Dn())}finally{z.p=g,S!==null&&k.types!==null&&(S.types=k.types),j.T=S}}function G1(){}function Hh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=qg(n).queue;Fg(n,m,r,B,l===null?G1:function(){return Wg(n),l(u)})}function qg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:B,baseState:B,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:B},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Wg(n){var r=qg(n);r.next===null&&(r=n.alternate.memoizedState),Bl(n,r.next.queue,{},Dn())}function Uh(){return $i(Zl)}function Gg(){return ci().memoizedState}function Yg(){return ci().memoizedState}function Y1(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Dn();n=os(l);var u=cs(r,n,l);u!==null&&(vn(u,r,l),jl(u,r,l)),r={cache:gh()},n.payload=r;return}r=r.return}}function K1(n,r,l){var u=Dn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pc(n)?Vg(r,l):(l=sh(n,r,l,u),l!==null&&(vn(l,n,u),Xg(l,r,u)))}function Kg(n,r,l){var u=Dn();Bl(n,r,l,u)}function Bl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(pc(n))Vg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var S=r.lastRenderedState,k=g(S,l);if(m.hasEagerState=!0,m.eagerState=k,Nn(k,S))return Ko(n,r,m,0),Ft===null&&Yo(),!1}catch{}finally{}if(l=sh(n,r,m,u),l!==null)return vn(l,n,u),Xg(l,r,u),!0}return!1}function $h(n,r,l,u){if(u={lane:2,revertLane:vd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},pc(n)){if(r)throw Error(s(479))}else r=sh(n,l,u,2),r!==null&&vn(r,n,2)}function pc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function Vg(n,r){Ba=lc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function Xg(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,te(n,l)}}var Ll={readContext:$i,use:uc,useCallback:ti,useContext:ti,useEffect:ti,useImperativeHandle:ti,useLayoutEffect:ti,useInsertionEffect:ti,useMemo:ti,useReducer:ti,useRef:ti,useState:ti,useDebugValue:ti,useDeferredValue:ti,useTransition:ti,useSyncExternalStore:ti,useId:ti,useHostTransitionStatus:ti,useFormState:ti,useActionState:ti,useOptimistic:ti,useMemoCache:ti,useCacheRefresh:ti};Ll.useEffectEvent=ti;var Zg={readContext:$i,use:uc,useCallback:function(n,r){return ln().memoizedState=[n,r===void 0?null:r],n},useContext:$i,useEffect:Bg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,dc(4194308,4,Pg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return dc(4194308,4,n,r)},useInsertionEffect:function(n,r){dc(4,2,n,r)},useMemo:function(n,r){var l=ln();r=r===void 0?null:r;var u=n();if(Ks){He(!0);try{n()}finally{He(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=ln();if(l!==void 0){var m=l(r);if(Ks){He(!0);try{l(r)}finally{He(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=K1.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=ln();return n={current:n},r.memoizedState=n},useState:function(n){n=Lh(n);var r=n.queue,l=Kg.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Ph,useDeferredValue:function(n,r){var l=ln();return Ih(l,n,r)},useTransition:function(){var n=Lh(!1);return n=Fg.bind(null,rt,n.queue,!0,!1),ln().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=ln();if(St){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(vt&127)!==0||xg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Bg(vg.bind(null,u,g,n),[n]),u.flags|=2048,Oa(9,{destroy:void 0},bg.bind(null,u,g,l,r),null),l},useId:function(){var n=ln(),r=Ft.identifierPrefix;if(St){var l=gr,u=mr;l=(u&~(1<<32-Oe(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=oc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}g[Je]=r,g[ot]=u;e:for(S=r.child;S!==null;){if(S.tag===5||S.tag===6)g.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===r)break e;for(;S.sibling===null;){if(S.return===null||S.return===r)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}r.stateNode=g;e:switch(qi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ir(r)}}return Kt(r),id(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Ir(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Na(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Ui,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Je]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||gx(n.nodeValue,l)),n||ss(r,!0)}else n=Bc(n).createTextNode(u),n[Je]=r,r.stateNode=n}return Kt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Na(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[Je]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Kt(r),n=!1}else l=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(An(r),r):(An(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Kt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Na(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[Je]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Kt(r),m=!1}else m=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(An(r),r):(An(r),null)}return An(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),bc(r,r.updateQueue),Kt(r),null);case 4:return be(),n===null&&Cd(r.stateNode.containerInfo),Kt(r),null;case 10:return Lr(r.type),Kt(r),null;case 19:if(Y(oi),u=r.memoizedState,u===null)return Kt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)zl(u,!1);else{if(ii!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=ac(n),g!==null){for(r.flags|=128,zl(u,!1),n=g.updateQueue,r.updateQueue=n,bc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Km(l,n),l=l.sibling;return C(oi,oi.current&1|2),St&&Dr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&wt()>Cc&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304)}else{if(!m)if(n=ac(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,bc(r,n),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!St)return Kt(r),null}else 2*wt()-u.renderingStartTime>Cc&&l!==536870912&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=wt(),n.sibling=null,l=oi.current,C(oi,m?l&1|2:l&1),St&&Dr(r,u.treeForkCount),n):(Kt(r),null);case 22:case 23:return An(r),kh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Kt(r),r.subtreeFlags&6&&(r.flags|=8192)):Kt(r),l=r.updateQueue,l!==null&&bc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&Y(qs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Lr(_i),Kt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function J1(n,r){switch(uh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Lr(_i),be(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Ee(r),null;case 31:if(r.memoizedState!==null){if(An(r),r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(An(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return Y(oi),null;case 4:return be(),null;case 10:return Lr(r.type),null;case 22:case 23:return An(r),kh(),n!==null&&Y(qs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Lr(_i),null;case 25:return null;default:return null}}function y_(n,r){switch(uh(r),r.tag){case 3:Lr(_i),be();break;case 26:case 27:case 5:Ee(r);break;case 4:be();break;case 31:r.memoizedState!==null&&An(r);break;case 13:An(r);break;case 19:Y(oi);break;case 10:Lr(r.type);break;case 22:case 23:An(r),kh(),n!==null&&Y(qs);break;case 24:Lr(_i)}}function Pl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,S=l.inst;u=g(),S.destroy=u}l=l.next}while(l!==m)}}catch(k){Ot(r,r.return,k)}}function ds(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var S=u.inst,k=S.destroy;if(k!==void 0){S.destroy=void 0,m=r;var D=l,V=k;try{V()}catch(le){Ot(m,D,le)}}}u=u.next}while(u!==g)}}catch(le){Ot(r,r.return,le)}}function S_(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{dg(r,l)}catch(u){Ot(n,n.return,u)}}}function w_(n,r,l){l.props=Vs(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Ot(n,r,u)}}function Il(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Ot(n,r,m)}}function _r(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Ot(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Ot(n,r,m)}else l.current=null}function C_(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Ot(n,n.return,m)}}function nd(n,r,l){try{var u=n.stateNode;yw(u,n.type,l,r),u[ot]=r}catch(m){Ot(n,n.return,m)}}function k_(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&bs(n.type)||n.tag===4}function rd(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||k_(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&bs(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function sd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=sn));else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(sd(n,r,l),n=n.sibling;n!==null;)sd(n,r,l),n=n.sibling}function vc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(vc(n,r,l),n=n.sibling;n!==null;)vc(n,r,l),n=n.sibling}function E_(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);qi(r,u,l),r[Je]=n,r[ot]=l}catch(g){Ot(n,n.return,g)}}var Hr=!1,vi=!1,ad=!1,N_=typeof WeakSet=="function"?WeakSet:Set,Ri=null;function ew(n,r){if(n=n.containerInfo,Nd=Uc,n=Im(n),Ju(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var S=0,k=-1,D=-1,V=0,le=0,fe=n,Q=null;t:for(;;){for(var ne;fe!==l||m!==0&&fe.nodeType!==3||(k=S+m),fe!==g||u!==0&&fe.nodeType!==3||(D=S+u),fe.nodeType===3&&(S+=fe.nodeValue.length),(ne=fe.firstChild)!==null;)Q=fe,fe=ne;for(;;){if(fe===n)break t;if(Q===l&&++V===m&&(k=S),Q===g&&++le===u&&(D=S),(ne=fe.nextSibling)!==null)break;fe=Q,Q=fe.parentNode}fe=ne}l=k===-1||D===-1?null:{start:k,end:D}}else l=null}l=l||{start:0,end:0}}else l=null;for(Td={focusedElem:n,selectionRange:l},Uc=!1,Ri=r;Ri!==null;)if(r=Ri,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Ri=n;else for(;Ri!==null;){switch(r=Ri,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),qi(g,u,l),g[Je]=n,ct(g),u=g;break e;case"link":var S=Dx("link","href",m).get(u+(l.href||""));if(S){for(var k=0;kHt&&(S=Ht,Ht=qe,qe=S);var q=zm(k,qe),P=zm(k,Ht);if(q&&P&&(ne.rangeCount!==1||ne.anchorNode!==q.node||ne.anchorOffset!==q.offset||ne.focusNode!==P.node||ne.focusOffset!==P.offset)){var K=fe.createRange();K.setStart(q.node,q.offset),ne.removeAllRanges(),qe>Ht?(ne.addRange(K),ne.extend(P.node,P.offset)):(K.setEnd(P.node,P.offset),ne.addRange(K))}}}}for(fe=[],ne=k;ne=ne.parentNode;)ne.nodeType===1&&fe.push({element:ne,left:ne.scrollLeft,top:ne.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,j.T=null,l=fd,fd=null;var g=gs,S=Wr;if(Ei=0,Ua=gs=null,Wr=0,(Rt&6)!==0)throw Error(s(331));var k=Rt;if(Rt|=4,P_(g.current),L_(g,g.current,S,l),Rt=k,Wl(0,!1),me&&typeof me.onPostCommitFiberRoot=="function")try{me.onPostCommitFiberRoot(Te,g)}catch{}return!0}finally{z.p=m,j.T=u,ix(n,r)}}function rx(n,r,l){r=Wn(l,r),r=Gh(n.stateNode,r,2),n=cs(n,r,2),n!==null&&(We(n,2),xr(n))}function Ot(n,r,l){if(n.tag===3)rx(n,n,l);else for(;r!==null;){if(r.tag===3){rx(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ms===null||!ms.has(u))){n=Wn(l,n),l=s_(2),u=cs(r,l,2),u!==null&&(a_(l,u,r,n),We(u,2),xr(u));break}}r=r.return}}function _d(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new nw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(cd=!0,m.add(l),n=ow.bind(null,n,r,l),r.then(n,n))}function ow(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(vt&l)===l&&(ii===4||ii===3&&(vt&62914560)===vt&&300>wt()-wc?(Rt&2)===0&&$a(n,0):ud|=l,Ha===vt&&(Ha=0)),xr(n)}function sx(n,r){r===0&&(r=de()),n=Is(n,r),n!==null&&(We(n,r),xr(n))}function cw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),sx(n,l)}function uw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),sx(n,l)}function hw(n,r){return Ve(n,r)}var Ac=null,qa=null,xd=!1,Rc=!1,bd=!1,xs=0;function xr(n){n!==qa&&n.next===null&&(qa===null?Ac=qa=n:qa=qa.next=n),Rc=!0,xd||(xd=!0,fw())}function Wl(n,r){if(!bd&&Rc){bd=!0;do for(var l=!1,u=Ac;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var S=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Oe(42|n)+1)-1,g&=m&~(S&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,cx(u,g))}else g=vt,g=fi(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Gt(u,g)||(l=!0,cx(u,g));u=u.next}while(l);bd=!1}}function dw(){ax()}function ax(){Rc=xd=!1;var n=0;xs!==0&&ww()&&(n=xs);for(var r=wt(),l=null,u=Ac;u!==null;){var m=u.next,g=lx(u,r);g===0?(u.next=null,l===null?Ac=m:l.next=m,m===null&&(qa=l)):(l=u,(n!==0||(g&3)!==0)&&(Rc=!0)),u=m}Ei!==0&&Ei!==5||Wl(n),xs!==0&&(xs=0)}function lx(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var le=D.transferSize,fe=D.initiatorType;le&&_x(fe)&&(D=D.responseEnd,S+=le*(D"u"?null:document;function jx(n,r,l){var u=Wa;if(u&&typeof r=="string"&&r){var m=ki(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),Tx.has(m)||(Tx.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),qi(r,"link",n),ct(r),u.head.appendChild(r)))}}function Mw(n){Gr.D(n),jx("dns-prefetch",n,null)}function Dw(n,r){Gr.C(n,r),jx("preconnect",n,r)}function Bw(n,r,l){Gr.L(n,r,l);var u=Wa;if(u&&n&&r){var m='link[rel="preload"][as="'+ki(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+ki(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+ki(l.imageSizes)+'"]')):m+='[href="'+ki(n)+'"]';var g=m;switch(r){case"style":g=Ga(n);break;case"script":g=Ya(n)}Zn.has(g)||(n=_({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),Zn.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(Vl(g))||r==="script"&&u.querySelector(Xl(g))||(r=u.createElement("link"),qi(r,"link",n),ct(r),u.head.appendChild(r)))}}function Lw(n,r){Gr.m(n,r);var l=Wa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+ki(u)+'"][href="'+ki(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ya(n)}if(!Zn.has(g)&&(n=_({rel:"modulepreload",href:n},r),Zn.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Xl(g)))return}u=l.createElement("link"),qi(u,"link",n),ct(u),l.head.appendChild(u)}}}function Ow(n,r,l){Gr.S(n,r,l);var u=Wa;if(u&&n){var m=nr(u).hoistableStyles,g=Ga(n);r=r||"default";var S=m.get(g);if(!S){var k={loading:0,preload:null};if(S=u.querySelector(Vl(g)))k.loading=5;else{n=_({rel:"stylesheet",href:n,"data-precedence":r},l),(l=Zn.get(g))&&Ld(n,l);var D=S=u.createElement("link");ct(D),qi(D,"link",n),D._p=new Promise(function(V,le){D.onload=V,D.onerror=le}),D.addEventListener("load",function(){k.loading|=1}),D.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Oc(S,r,u)}S={type:"stylesheet",instance:S,count:1,state:k},m.set(g,S)}}}function zw(n,r){Gr.X(n,r);var l=Wa;if(l&&n){var u=nr(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=_({src:n,async:!0},r),(r=Zn.get(m))&&Od(n,r),g=l.createElement("script"),ct(g),qi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Pw(n,r){Gr.M(n,r);var l=Wa;if(l&&n){var u=nr(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=_({src:n,async:!0,type:"module"},r),(r=Zn.get(m))&&Od(n,r),g=l.createElement("script"),ct(g),qi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Ax(n,r,l,u){var m=(m=oe.current)?Lc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Ga(l.href),l=nr(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Ga(l.href);var g=nr(m).hoistableStyles,S=g.get(n);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,S),(g=m.querySelector(Vl(n)))&&!g._p&&(S.instance=g,S.state.loading=5),Zn.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Zn.set(n,l),g||Iw(m,n,l,S.state))),r&&u===null)throw Error(s(528,""));return S}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ya(l),l=nr(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Ga(n){return'href="'+ki(n)+'"'}function Vl(n){return'link[rel="stylesheet"]['+n+"]"}function Rx(n){return _({},n,{"data-precedence":n.precedence,precedence:null})}function Iw(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),qi(r,"link",l),ct(r),n.head.appendChild(r))}function Ya(n){return'[src="'+ki(n)+'"]'}function Xl(n){return"script[async]"+n}function Mx(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+ki(l.href)+'"]');if(u)return r.instance=u,ct(u),u;var m=_({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),ct(u),qi(u,"style",m),Oc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ga(l.href);var g=n.querySelector(Vl(m));if(g)return r.state.loading|=4,r.instance=g,ct(g),g;u=Rx(l),(m=Zn.get(m))&&Ld(u,m),g=(n.ownerDocument||n).createElement("link"),ct(g);var S=g;return S._p=new Promise(function(k,D){S.onload=k,S.onerror=D}),qi(g,"link",u),r.state.loading|=4,Oc(g,l.precedence,n),r.instance=g;case"script":return g=Ya(l.src),(m=n.querySelector(Xl(g)))?(r.instance=m,ct(m),m):(u=l,(m=Zn.get(g))&&(u=_({},l),Od(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),ct(m),qi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,Oc(u,l.precedence,n));return r.instance}function Oc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,S=0;S title"):null)}function Hw(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function Lx(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Uw(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Ga(u.href),g=r.querySelector(Vl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Pc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,ct(g);return}g=r.ownerDocument||r,u=Rx(u),(m=Zn.get(m))&&Ld(u,m),g=g.createElement("link"),ct(g);var S=g;S._p=new Promise(function(k,D){S.onload=k,S.onerror=D}),qi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Pc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var zd=0;function $w(n,r){return n.stylesheets&&n.count===0&&Hc(n,n.stylesheets),0zd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Pc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Ic=null;function Hc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Ic=new Map,r.forEach(Fw,n),Ic=null,Pc.call(n))}function Fw(n,r){if(!(r.state.loading&4)){var l=Ic.get(n);if(l)var u=l.get(null);else{l=new Map,Ic.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Gd.exports=aC(),Gd.exports}var oC=lC();const cC=Du(oC);function uC({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const d=await e(t);d&&a(d),c(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsxs("div",{className:"w-full max-w-sm",children:[f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),f.jsxs("form",{onSubmit:h,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&f.jsx("p",{className:"text-error text-xs",children:s}),f.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),f.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function hC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),d=async x=>{if(x.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const _=await e(t);_&&c(_),p(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsx("div",{className:"w-full max-w-sm",children:f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),f.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),f.jsxs("form",{onSubmit:d,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:x=>i(x.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),f.jsx("input",{type:"password",value:s,onChange:x=>a(x.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&f.jsx("p",{className:"text-error text-xs",children:o}),f.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const Xd="http://localhost:7777";function yy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[d,x]=w.useState(null),_=w.useCallback((N,L)=>fetch(N,{...L,headers:{...L==null?void 0:L.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{_(`${Xd}/api/wallet`).then(N=>N.json()).then(N=>i(N)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[_]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),x(null);try{const N=await _(`${Xd}/api/wallet/create`,{method:"POST"}),L=await N.json();if(!N.ok)throw new Error(L.error||"Creation failed");b()}catch(N){x(N instanceof Error?N.message:"Failed to create wallet")}a(!1)},y=async N=>{c(N.walletId||N.name),x(null);try{const L=await _(`${Xd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:N.walletId,name:N.name,address:N.normalizedAddress||N.address})}),O=await L.json();if(!L.ok)throw new Error(O.error||"Wallet switch failed");b()}catch(L){x(L instanceof Error?L.message:"Failed to switch wallet")}c(null)},E=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},A=N=>`${N.slice(0,6)}...${N.slice(-4)}`;return f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&f.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),d&&f.jsx("p",{className:"text-error text-xs",children:d}),f.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&f.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(N=>f.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:N.name}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:N.address||"No EVM address"})]}),f.jsx("button",{onClick:()=>y(N),disabled:!N.address||o===(N.walletId||N.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(N.walletId||N.name)?"switching...":"use"})]},N.walletId||N.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),t&&t.exists&&t.address&&f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),f.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Name"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:A(t.address)}),f.jsx("button",{onClick:E,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),f.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC"}),f.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"PLOT"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Network"}),f.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&f.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[f.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(N=>f.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsxs("p",{className:N.active?"text-accent truncate font-medium":"text-foreground truncate",children:[N.name,N.active?" (active)":""]}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:N.address||"No EVM address"})]}),!N.active&&f.jsx("button",{onClick:()=>y(N),disabled:!N.address||o===(N.walletId||N.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(N.walletId||N.name)?"...":"use"})]},N.walletId||N.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),f.jsxs("div",{className:"border-border border-t pt-3",children:[f.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),f.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),f.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&f.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Su(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const zp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function dC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,d]=w.useState(!1),[x,_]=w.useState(!1),[b,v]=w.useState(null),[y,E]=w.useState("AI Writer"),[A,N]=w.useState(""),[L,O]=w.useState(""),[J,$]=w.useState(!1),[M,X]=w.useState(null),[he,ye]=w.useState(""),[U,se]=w.useState(null),[W,G]=w.useState(!1),[Z,I]=w.useState(null),[j,z]=w.useState(null),[B,_e]=w.useState(null),T=w.useCallback((ie,oe)=>fetch(ie,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(ie=>ie.json()).then(ie=>v(ie)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(ie=>ie.ok?ie.json():null).then(ie=>{ie&&_e(ie)}).catch(()=>{})},[]);const R=async()=>{if(!y.trim()){X("Agent name is required");return}if(!A.trim()){X("Description is required");return}$(!0),X(null);try{const ie=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:y,description:A,...L.trim()&&{genre:L}})}),oe=await ie.json();if(!ie.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ie){X(ie instanceof Error?ie.message:"Registration failed")}$(!1)},Y=async()=>{if(!he.trim()||!/^0x[a-fA-F0-9]{40}$/.test(he)){I("Enter a valid wallet address (0x...)");return}G(!0),I(null),se(null);try{const ie=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:he})}),oe=await ie.json();if(!ie.ok)throw new Error(oe.error||"Failed to generate binding code");se(oe)}catch(ie){I(ie instanceof Error?ie.message:"Failed to generate binding code")}G(!1)},C=async(ie,oe)=>{await navigator.clipboard.writeText(ie),z(oe),setTimeout(()=>z(null),2e3)},ae=async()=>{if(h(null),d(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}_(!0);try{const ie=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ie.ok){const oe=await ie.json();throw new Error(oe.error||"Reset failed")}d(!0),s(""),o(""),setTimeout(()=>d(!1),3e3)}catch(ie){h(ie instanceof Error?ie.message:"Reset failed")}_(!1)};return f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),f.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),f.jsx("input",{value:y,onChange:ie=>E(ie.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),f.jsx("input",{value:A,onChange:ie=>N(ie.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),f.jsx("input",{value:L,onChange:ie=>O(ie.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),M&&f.jsx("p",{className:"text-error text-xs",children:M}),f.jsx("button",{onClick:R,disabled:J||!y.trim()||!A.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:J?"Registering...":"Register Agent Identity"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.claude.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.codex.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),f.jsx("span",{className:"text-muted text-xs font-mono",children:(B==null?void 0:B.codex.version)??"—"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),f.jsx("span",{className:"text-muted text-xs",children:(B==null?void 0:B.codex.imageGeneration)??"unknown"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),f.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:B!=null&&B.codex.installed?B.codex.auth==="ok"?"ok":"unclear":"—"})]}),Su(B)&&f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:zp}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.checkedAt?new Date(B.checkedAt).toLocaleString():"—"})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?f.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",f.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),f.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[f.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),f.jsx("p",{children:'2. Click "Generate Binding Code"'}),f.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),f.jsx("input",{value:he,onChange:ie=>ye(ie.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),Z&&f.jsx("p",{className:"text-error text-xs",children:Z}),f.jsx("button",{onClick:Y,disabled:W||!he.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"Generating...":"Generate Binding Code"}),U&&f.jsxs("div",{className:"space-y-3 mt-3",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.signature}),f.jsx("button",{onClick:()=>C(U.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="signature"?"Copied!":"Copy"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.owsWallet}),f.jsx("button",{onClick:()=>C(U.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="wallet"?"Copied!":"Copy"})]})]}),U.agentId&&f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:U.agentId}),f.jsx("button",{onClick:()=>C(String(U.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="agentId"?"Copied!":"Copy"})]})]}),f.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),f.jsx(yy,{token:e}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("input",{type:"password",value:i,onChange:ie=>s(ie.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),f.jsx("input",{type:"password",value:a,onChange:ie=>o(ie.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&f.jsx("p",{className:"text-error text-xs",children:c}),p&&f.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),f.jsx("button",{onClick:ae,disabled:x||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:x?"updating...":"update passphrase"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),f.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const fC="http://localhost:7777";function pC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${fC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?f.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),f.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),f.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Active wallet"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Address"}),f.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH Balance"}),f.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC Balance"}),f.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),f.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Royalties earned"}),f.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),f.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),f.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[f.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),f.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Stories published"}),f.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?f.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):f.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>f.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[f.jsxs("div",{className:"flex items-start justify-between",children:[f.jsxs("div",{children:[h.genre&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),f.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),f.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&f.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),f.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),f.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),f.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),f.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>f.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),f.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&f.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),f.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[f.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&f.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&f.jsx("div",{className:"border-border rounded border p-4",children:f.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):f.jsx("div",{className:"flex h-full items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const mC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},gC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function _C({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,d]=w.useState([]),[x,_]=w.useState(new Set),[b,v]=w.useState(!1),y=w.useCallback(async()=>{try{const $=await e("/api/stories");if($.ok){const M=await $.json();h(M.stories)}}catch{}},[e]),E=w.useCallback(async()=>{try{const $=await e("/api/stories/archived");if($.ok){const M=await $.json();d(M.stories)}}catch{}},[e]),A=w.useCallback(async $=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$})})).ok&&(E(),y())}catch{}},[e,E,y]);w.useEffect(()=>{y();const $=setInterval(y,5e3);return()=>clearInterval($)},[y]),w.useEffect(()=>{b&&E()},[b,E]),w.useEffect(()=>{t&&_($=>new Set($).add(t))},[t]);const N=$=>{_(M=>{const X=new Set(M);return X.has($)?X.delete($):X.add($),X})},L=$=>{var X;const M=$.map(he=>{var ye;return{file:he.file,num:(ye=he.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(he=>he.num!=null).sort((he,ye)=>parseInt(ye.num)-parseInt(he.num));return M.length>0?M[0].file:$.some(he=>he.file==="genesis.md")?"genesis.md":$.some(he=>he.file==="structure.md")?"structure.md":((X=$[0])==null?void 0:X.file)??null},O=$=>{if(N($.name),$.contentType==="cartoon")s($.name,"");else{const M=L($.files);M&&s($.name,M)}},J=$=>{const M=X=>{if(X==="structure.md")return 0;if(X==="genesis.md")return 1;const he=X.match(/^plot-(\d+)\.md$/);return he?2+parseInt(he[1]):100};return[...$].sort((X,he)=>M(X.file)-M(he.file))};return b?f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),f.jsx("span",{className:"text-xs text-muted",children:p.length})]}),f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[f.jsx("span",{children:"←"}),f.jsx("span",{children:"Back"})]})}),f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?f.jsx("div",{className:"p-3 text-sm text-muted",children:f.jsx("p",{children:"No archived stories."})}):p.map($=>f.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[f.jsx("span",{className:"text-sm font-medium truncate",title:$.name,children:$.title||$.name}),f.jsx("button",{onClick:()=>A($.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},$.name))})]}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),f.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[f.jsx("span",{children:"+"}),f.jsx("span",{children:"New Story"})]})}),f.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map($=>f.jsx("div",{children:f.jsxs("button",{onClick:()=>s($,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===$?"bg-surface":""}`,children:[f.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),f.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},$)),c.length===0&&o.length===0?f.jsxs("div",{className:"p-3 text-sm text-muted",children:[f.jsx("p",{children:"No stories yet."}),f.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter($=>$.name!=="_example").map($=>f.jsxs("div",{children:[f.jsxs("button",{onClick:()=>O($),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[f.jsx("span",{className:"text-xs text-muted",children:x.has($.name)?"▼":"▶"}),f.jsx("span",{className:"font-medium truncate",title:$.name,children:$.title||$.name}),$.contentType==="cartoon"&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),f.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[$.publishedCount,"/",$.files.length]})]}),x.has($.name)&&f.jsx("div",{className:"pl-4",children:J($.files).map(M=>{const X=t===$.name&&i===M.file;return f.jsxs("button",{onClick:()=>s($.name,M.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${X?"bg-surface font-medium":""}`,children:[f.jsx("span",{className:gC[M.status],children:mC[M.status]}),f.jsx("span",{className:"truncate font-mono",children:M.file})]},M.file)})})]},$.name))]}),f.jsx("div",{className:"px-3 py-2 border-t border-border",children:f.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:f.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var Ae=Object.prototype.hasOwnProperty,Ve=e.unstable_scheduleCallback,At=e.unstable_cancelCallback,Ot=e.unstable_shouldYield,ci=e.unstable_requestPaint,St=e.unstable_now,fi=e.unstable_getCurrentPriorityLevel,ne=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Pe=e.unstable_NormalPriority,Fe=e.unstable_LowPriority,Qe=e.unstable_IdlePriority,H=e.log,ge=e.unstable_setDisableYieldValue,Te=null,me=null;function He(n){if(typeof H=="function"&&ge(n),me&&typeof me.setStrictMode=="function")try{me.setStrictMode(Te,n)}catch{}}var Le=Math.clz32?Math.clz32:Mt,ht=Math.log,it=Math.LN2;function Mt(n){return n>>>=0,n===0?32:31-(ht(n)/it|0)|0}var Dt=256,pi=262144,kt=4194304;function ki(n){var r=n&42;if(r!==0)return r;switch(n&-n){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 n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function mi(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,S=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=ki(u):(S&=k,S!==0?m=ki(S):l||(l=k&~n,l!==0&&(m=ki(l))))):(k=u&~g,k!==0?m=ki(k):S!==0?m=ki(S):l||(l=u&~n,l!==0&&(m=ki(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function Gt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function mn(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+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 r+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 de(){var n=kt;return kt<<=1,(kt&62914560)===0&&(kt=4194304),n}function Re(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function We(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function st(n,r,l,u,m,g){var S=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,M=n.expirationTimes,V=n.hiddenUpdates;for(l=S&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var da=/[\n"\\]/g;function Ei(n){return n.replace(da,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function fa(n,r,l,u,m,g,S,k){n.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?n.type=S:n.removeAttribute("type"),r!=null?S==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Xi(r)):n.value!==""+Xi(r)&&(n.value=""+Xi(r)):S!=="submit"&&S!=="reset"||n.removeAttribute("value"),r!=null?ma(n,S,Xi(r)):l!=null?ma(n,S,Xi(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+Xi(k):n.removeAttribute("name")}function pa(n,r,l,u,m,g,S,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){lr(n);return}l=l!=null?""+Xi(l):"",r=r!=null?""+Xi(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(n.name=S),lr(n)}function ma(n,r,l){r==="number"&&an(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Wn(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),xi=!1;if(Et)try{var Rn={};Object.defineProperty(Rn,"passive",{get:function(){xi=!0}}),window.addEventListener("test",Rn,Rn),window.removeEventListener("test",Rn,Rn)}catch{xi=!1}var on=null,cr=null,Ls=null;function vm(){if(Ls)return Ls;var n,r=cr,l=r.length,u,m="value"in on?on.value:on.textContent,g=m.length;for(n=0;n=_l),Em=" ",Nm=!1;function Tm(n,r){switch(n){case"keyup":return S1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var ba=!1;function C1(n,r){switch(n){case"compositionend":return jm(r);case"keypress":return r.which!==32?null:(Nm=!0,Em);case"textInput":return n=r.data,n===Em&&Nm?null:n;default:return null}}function k1(n,r){if(ba)return n==="compositionend"||!Xu&&Tm(n,r)?(n=vm(),Ls=cr=on=null,ba=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=zm(l)}}function Im(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Im(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Hm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=an(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=an(n.document)}return r}function Ju(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var D1=Et&&"documentMode"in document&&11>=document.documentMode,va=null,eh=null,Sl=null,th=!1;function Um(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;th||va==null||va!==an(u)||(u=va,"selectionStart"in u&&Ju(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Sl&&yl(Sl,u)||(Sl=u,u=Dc(eh,"onSelect"),0>=S,m-=S,gr=1<<32-Le(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var Tt=Q(F,Ie,K[lt],ce);if(Tt===null){Ie===null&&(Ie=vt);break}n&&Ie&&Tt.alternate===null&&r(F,Ie),z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt,Ie=vt}if(lt===K.length)return l(F,Ie),yt&&Dr(F,lt),Ue;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Cs=Q(F,Ie,Tt.value,ce);if(Cs===null){Ie===null&&(Ie=vt);break}n&&Ie&&Cs.alternate===null&&r(F,Ie),z=g(Cs,z,lt),Nt===null?Ue=Cs:Nt.sibling=Cs,Nt=Cs,Ie=vt}if(Tt.done)return l(F,Ie),yt&&Dr(F,lt),Ue;if(Ie===null){for(;!Tt.done;lt++,Tt=K.next())Tt=fe(F,Tt.value,ce),Tt!==null&&(z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt);return yt&&Dr(F,lt),Ue}for(Ie=u(Ie);!Tt.done;lt++,Tt=K.next())Tt=ie(Ie,F,lt,Tt.value,ce),Tt!==null&&(n&&Tt.alternate!==null&&Ie.delete(Tt.key===null?lt:Tt.key),z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt);return n&&Ie.forEach(function(Jw){return r(F,Jw)}),yt&&Dr(F,lt),Ue}function Ht(F,z,K,ce){if(typeof K=="object"&&K!==null&&K.type===N&&K.key===null&&(K=K.props.children),typeof K=="object"&&K!==null){switch(K.$$typeof){case v:e:{for(var Ue=K.key;z!==null;){if(z.key===Ue){if(Ue=K.type,Ue===N){if(z.tag===7){l(F,z.sibling),ce=m(z,K.props.children),ce.return=F,F=ce;break e}}else if(z.elementType===Ue||typeof Ue=="object"&&Ue!==null&&Ue.$$typeof===he&&Ws(Ue)===z.type){l(F,z.sibling),ce=m(z,K.props),Tl(ce,K),ce.return=F,F=ce;break e}l(F,z);break}else r(F,z);z=z.sibling}K.type===N?(ce=Hs(K.props.children,F.mode,ce,K.key),ce.return=F,F=ce):(ce=Xo(K.type,K.key,K.props,null,F.mode,ce),Tl(ce,K),ce.return=F,F=ce)}return S(F);case y:e:{for(Ue=K.key;z!==null;){if(z.key===Ue)if(z.tag===4&&z.stateNode.containerInfo===K.containerInfo&&z.stateNode.implementation===K.implementation){l(F,z.sibling),ce=m(z,K.children||[]),ce.return=F,F=ce;break e}else{l(F,z);break}else r(F,z);z=z.sibling}ce=oh(K,F.mode,ce),ce.return=F,F=ce}return S(F);case he:return K=Ws(K),Ht(F,z,K,ce)}if(I(K))return Oe(F,z,K,ce);if(W(K)){if(Ue=W(K),typeof Ue!="function")throw Error(s(150));return K=Ue.call(K),qe(F,z,K,ce)}if(typeof K.then=="function")return Ht(F,z,nc(K),ce);if(K.$$typeof===P)return Ht(F,z,Jo(F,K),ce);rc(F,K)}return typeof K=="string"&&K!==""||typeof K=="number"||typeof K=="bigint"?(K=""+K,z!==null&&z.tag===6?(l(F,z.sibling),ce=m(z,K),ce.return=F,F=ce):(l(F,z),ce=lh(K,F.mode,ce),ce.return=F,F=ce),S(F)):l(F,z)}return function(F,z,K,ce){try{Nl=0;var Ue=Ht(F,z,K,ce);return Ra=null,Ue}catch(Ie){if(Ie===Aa||Ie===tc)throw Ie;var Nt=Dn(29,Ie,null,F.mode);return Nt.lanes=ce,Nt.return=F,Nt}finally{}}}var Ys=ug(!0),hg=ug(!1),ls=!1;function vh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function yh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function os(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function cs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(jt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=Vo(n),Km(n,null,l),r}return Ko(n,u,r,l),Vo(n)}function jl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ct(n,l)}}function Sh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=S:g=g.next=S,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var wh=!1;function Al(){if(wh){var n=ja;if(n!==null)throw n}}function Rl(n,r,l,u){wh=!1;var m=n.updateQueue;ls=!1;var g=m.firstBaseUpdate,S=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var M=k,V=M.next;M.next=null,S===null?g=V:S.next=V,S=M;var le=n.alternate;le!==null&&(le=le.updateQueue,k=le.lastBaseUpdate,k!==S&&(k===null?le.firstBaseUpdate=V:k.next=V,le.lastBaseUpdate=M))}if(g!==null){var fe=m.baseState;S=0,le=V=M=null,k=g;do{var Q=k.lane&-536870913,ie=Q!==k.lane;if(ie?(bt&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ta&&(wh=!0),le!==null&&(le=le.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=n,qe=k;Q=r;var Ht=l;switch(qe.tag){case 1:if(Oe=qe.payload,typeof Oe=="function"){fe=Oe.call(Ht,fe,Q);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=qe.payload,Q=typeof Oe=="function"?Oe.call(Ht,fe,Q):Oe,Q==null)break e;fe=x({},fe,Q);break e;case 2:ls=!0}}Q=k.callback,Q!==null&&(n.flags|=64,ie&&(n.flags|=8192),ie=m.callbacks,ie===null?m.callbacks=[Q]:ie.push(Q))}else ie={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},le===null?(V=le=ie,M=fe):le=le.next=ie,S|=Q;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ie=k,k=ie.next,ie.next=null,m.lastBaseUpdate=ie,m.shared.pending=null}}while(!0);le===null&&(M=fe),m.baseState=M,m.firstBaseUpdate=V,m.lastBaseUpdate=le,g===null&&(m.shared.lanes=0),ps|=S,n.lanes=S,n.memoizedState=fe}}function dg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function fg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var S=j.T,k={};j.T=k,$h(n,!1,r,l);try{var M=m(),V=j.S;if(V!==null&&V(k,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var le=$1(M,u);Bl(n,r,le,Pn(n))}else Bl(n,r,u,Pn(n))}catch(fe){Bl(n,r,{then:function(){},status:"rejected",reason:fe},Pn())}finally{O.p=g,S!==null&&k.types!==null&&(S.types=k.types),j.T=S}}function K1(){}function Hh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Wg(n).queue;qg(n,m,r,B,l===null?K1:function(){return Gg(n),l(u)})}function Wg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:B,baseState:B,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:B},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Gg(n){var r=Wg(n);r.next===null&&(r=n.alternate.memoizedState),Bl(n,r.next.queue,{},Pn())}function Uh(){return qi(Zl)}function Yg(){return hi().memoizedState}function Kg(){return hi().memoizedState}function V1(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Pn();n=os(l);var u=cs(r,n,l);u!==null&&(wn(u,r,l),jl(u,r,l)),r={cache:gh()},n.payload=r;return}r=r.return}}function X1(n,r,l){var u=Pn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pc(n)?Xg(r,l):(l=sh(n,r,l,u),l!==null&&(wn(l,n,u),Zg(l,r,u)))}function Vg(n,r,l){var u=Pn();Bl(n,r,l,u)}function Bl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(pc(n))Xg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var S=r.lastRenderedState,k=g(S,l);if(m.hasEagerState=!0,m.eagerState=k,Mn(k,S))return Ko(n,r,m,0),$t===null&&Yo(),!1}catch{}finally{}if(l=sh(n,r,m,u),l!==null)return wn(l,n,u),Zg(l,r,u),!0}return!1}function $h(n,r,l,u){if(u={lane:2,revertLane:vd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},pc(n)){if(r)throw Error(s(479))}else r=sh(n,l,u,2),r!==null&&wn(r,n,2)}function pc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function Xg(n,r){Da=lc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function Zg(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ct(n,l)}}var Ll={readContext:qi,use:uc,useCallback:ri,useContext:ri,useEffect:ri,useImperativeHandle:ri,useLayoutEffect:ri,useInsertionEffect:ri,useMemo:ri,useReducer:ri,useRef:ri,useState:ri,useDebugValue:ri,useDeferredValue:ri,useTransition:ri,useSyncExternalStore:ri,useId:ri,useHostTransitionStatus:ri,useFormState:ri,useActionState:ri,useOptimistic:ri,useMemoCache:ri,useCacheRefresh:ri};Ll.useEffectEvent=ri;var Qg={readContext:qi,use:uc,useCallback:function(n,r){return cn().memoizedState=[n,r===void 0?null:r],n},useContext:qi,useEffect:Lg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,dc(4194308,4,Ig.bind(null,r,n),l)},useLayoutEffect:function(n,r){return dc(4194308,4,n,r)},useInsertionEffect:function(n,r){dc(4,2,n,r)},useMemo:function(n,r){var l=cn();r=r===void 0?null:r;var u=n();if(Ks){He(!0);try{n()}finally{He(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=cn();if(l!==void 0){var m=l(r);if(Ks){He(!0);try{l(r)}finally{He(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=X1.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=cn();return n={current:n},r.memoizedState=n},useState:function(n){n=Lh(n);var r=n.queue,l=Vg.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Ph,useDeferredValue:function(n,r){var l=cn();return Ih(l,n,r)},useTransition:function(){var n=Lh(!1);return n=qg.bind(null,rt,n.queue,!0,!1),cn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=cn();if(yt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),$t===null)throw Error(s(349));(bt&127)!==0||bg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Lg(yg.bind(null,u,g,n),[n]),u.flags|=2048,La(9,{destroy:void 0},vg.bind(null,u,g,l,r),null),l},useId:function(){var n=cn(),r=$t.identifierPrefix;if(yt){var l=xr,u=gr;l=(u&~(1<<32-Le(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=oc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}g[ut]=r,g[at]=u;e:for(S=r.child;S!==null;){if(S.tag===5||S.tag===6)g.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===r)break e;for(;S.sibling===null;){if(S.return===null||S.return===r)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}r.stateNode=g;e:switch(Gi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ir(r)}}return Vt(r),id(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Ir(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ea(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Fi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[ut]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||x_(n.nodeValue,l)),n||ss(r,!0)}else n=Bc(n).createTextNode(u),n[ut]=r,r.stateNode=n}return Vt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ea(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[ut]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Vt(r),n=!1}else l=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Ln(r),r):(Ln(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Vt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ea(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[ut]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Vt(r),m=!1}else m=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Ln(r),r):(Ln(r),null)}return Ln(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),bc(r,r.updateQueue),Vt(r),null);case 4:return be(),n===null&&Cd(r.stateNode.containerInfo),Vt(r),null;case 10:return Lr(r.type),Vt(r),null;case 19:if(Y(ui),u=r.memoizedState,u===null)return Vt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)zl(u,!1);else{if(si!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=ac(n),g!==null){for(r.flags|=128,zl(u,!1),n=g.updateQueue,r.updateQueue=n,bc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Vm(l,n),l=l.sibling;return C(ui,ui.current&1|2),yt&&Dr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&St()>Cc&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304)}else{if(!m)if(n=ac(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,bc(r,n),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!yt)return Vt(r),null}else 2*St()-u.renderingStartTime>Cc&&l!==536870912&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=St(),n.sibling=null,l=ui.current,C(ui,m?l&1|2:l&1),yt&&Dr(r,u.treeForkCount),n):(Vt(r),null);case 22:case 23:return Ln(r),kh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Vt(r),r.subtreeFlags&6&&(r.flags|=8192)):Vt(r),l=r.updateQueue,l!==null&&bc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&Y(qs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Lr(_i),Vt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function tw(n,r){switch(uh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Lr(_i),be(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Ee(r),null;case 31:if(r.memoizedState!==null){if(Ln(r),r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Ln(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return Y(ui),null;case 4:return be(),null;case 10:return Lr(r.type),null;case 22:case 23:return Ln(r),kh(),n!==null&&Y(qs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Lr(_i),null;case 25:return null;default:return null}}function Sx(n,r){switch(uh(r),r.tag){case 3:Lr(_i),be();break;case 26:case 27:case 5:Ee(r);break;case 4:be();break;case 31:r.memoizedState!==null&&Ln(r);break;case 13:Ln(r);break;case 19:Y(ui);break;case 10:Lr(r.type);break;case 22:case 23:Ln(r),kh(),n!==null&&Y(qs);break;case 24:Lr(_i)}}function Pl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,S=l.inst;u=g(),S.destroy=u}l=l.next}while(l!==m)}}catch(k){Lt(r,r.return,k)}}function ds(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var S=u.inst,k=S.destroy;if(k!==void 0){S.destroy=void 0,m=r;var M=l,V=k;try{V()}catch(le){Lt(m,M,le)}}}u=u.next}while(u!==g)}}catch(le){Lt(r,r.return,le)}}function wx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{fg(r,l)}catch(u){Lt(n,n.return,u)}}}function Cx(n,r,l){l.props=Vs(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Lt(n,r,u)}}function Il(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Lt(n,r,m)}}function _r(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Lt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Lt(n,r,m)}else l.current=null}function kx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Lt(n,n.return,m)}}function nd(n,r,l){try{var u=n.stateNode;ww(u,n.type,l,r),u[at]=r}catch(m){Lt(n,n.return,m)}}function Ex(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&bs(n.type)||n.tag===4}function rd(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Ex(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&bs(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function sd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=ln));else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(sd(n,r,l),n=n.sibling;n!==null;)sd(n,r,l),n=n.sibling}function vc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(vc(n,r,l),n=n.sibling;n!==null;)vc(n,r,l),n=n.sibling}function Nx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Gi(r,u,l),r[ut]=n,r[at]=l}catch(g){Lt(n,n.return,g)}}var Hr=!1,yi=!1,ad=!1,Tx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function iw(n,r){if(n=n.containerInfo,Nd=Uc,n=Hm(n),Ju(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var S=0,k=-1,M=-1,V=0,le=0,fe=n,Q=null;t:for(;;){for(var ie;fe!==l||m!==0&&fe.nodeType!==3||(k=S+m),fe!==g||u!==0&&fe.nodeType!==3||(M=S+u),fe.nodeType===3&&(S+=fe.nodeValue.length),(ie=fe.firstChild)!==null;)Q=fe,fe=ie;for(;;){if(fe===n)break t;if(Q===l&&++V===m&&(k=S),Q===g&&++le===u&&(M=S),(ie=fe.nextSibling)!==null)break;fe=Q,Q=fe.parentNode}fe=ie}l=k===-1||M===-1?null:{start:k,end:M}}else l=null}l=l||{start:0,end:0}}else l=null;for(Td={focusedElem:n,selectionRange:l},Uc=!1,Mi=r;Mi!==null;)if(r=Mi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Mi=n;else for(;Mi!==null;){switch(r=Mi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),Gi(g,u,l),g[ut]=n,ti(g),u=g;break e;case"link":var S=B_("link","href",m).get(u+(l.href||""));if(S){for(var k=0;kHt&&(S=Ht,Ht=qe,qe=S);var F=Pm(k,qe),z=Pm(k,Ht);if(F&&z&&(ie.rangeCount!==1||ie.anchorNode!==F.node||ie.anchorOffset!==F.offset||ie.focusNode!==z.node||ie.focusOffset!==z.offset)){var K=fe.createRange();K.setStart(F.node,F.offset),ie.removeAllRanges(),qe>Ht?(ie.addRange(K),ie.extend(z.node,z.offset)):(K.setEnd(z.node,z.offset),ie.addRange(K))}}}}for(fe=[],ie=k;ie=ie.parentNode;)ie.nodeType===1&&fe.push({element:ie,left:ie.scrollLeft,top:ie.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,j.T=null,l=fd,fd=null;var g=gs,S=Wr;if(Ni=0,Ha=gs=null,Wr=0,(jt&6)!==0)throw Error(s(331));var k=jt;if(jt|=4,Ix(g.current),Ox(g,g.current,S,l),jt=k,Wl(0,!1),me&&typeof me.onPostCommitFiberRoot=="function")try{me.onPostCommitFiberRoot(Te,g)}catch{}return!0}finally{O.p=m,j.T=u,n_(n,r)}}function s_(n,r,l){r=Kn(l,r),r=Gh(n.stateNode,r,2),n=cs(n,r,2),n!==null&&(We(n,2),br(n))}function Lt(n,r,l){if(n.tag===3)s_(n,n,l);else for(;r!==null;){if(r.tag===3){s_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ms===null||!ms.has(u))){n=Kn(l,n),l=ax(2),u=cs(r,l,2),u!==null&&(lx(l,u,r,n),We(u,2),br(u));break}}r=r.return}}function xd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new sw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(cd=!0,m.add(l),n=uw.bind(null,n,r,l),r.then(n,n))}function uw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,$t===n&&(bt&l)===l&&(si===4||si===3&&(bt&62914560)===bt&&300>St()-wc?(jt&2)===0&&Ua(n,0):ud|=l,Ia===bt&&(Ia=0)),br(n)}function a_(n,r){r===0&&(r=de()),n=Is(n,r),n!==null&&(We(n,r),br(n))}function hw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),a_(n,l)}function dw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),a_(n,l)}function fw(n,r){return Ve(n,r)}var Ac=null,Fa=null,_d=!1,Rc=!1,bd=!1,_s=0;function br(n){n!==Fa&&n.next===null&&(Fa===null?Ac=Fa=n:Fa=Fa.next=n),Rc=!0,_d||(_d=!0,mw())}function Wl(n,r){if(!bd&&Rc){bd=!0;do for(var l=!1,u=Ac;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var S=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Le(42|n)+1)-1,g&=m&~(S&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,u_(u,g))}else g=bt,g=mi(u,u===$t?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Gt(u,g)||(l=!0,u_(u,g));u=u.next}while(l);bd=!1}}function pw(){l_()}function l_(){Rc=_d=!1;var n=0;_s!==0&&kw()&&(n=_s);for(var r=St(),l=null,u=Ac;u!==null;){var m=u.next,g=o_(u,r);g===0?(u.next=null,l===null?Ac=m:l.next=m,m===null&&(Fa=l)):(l=u,(n!==0||(g&3)!==0)&&(Rc=!0)),u=m}Ni!==0&&Ni!==5||Wl(n),_s!==0&&(_s=0)}function o_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var le=M.transferSize,fe=M.initiatorType;le&&__(fe)&&(M=M.responseEnd,S+=le*(M"u"?null:document;function A_(n,r,l){var u=qa;if(u&&typeof r=="string"&&r){var m=Ei(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),j_.has(m)||(j_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Gi(r,"link",n),ti(r),u.head.appendChild(r)))}}function Bw(n){Gr.D(n),A_("dns-prefetch",n,null)}function Lw(n,r){Gr.C(n,r),A_("preconnect",n,r)}function Ow(n,r,l){Gr.L(n,r,l);var u=qa;if(u&&n&&r){var m='link[rel="preload"][as="'+Ei(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Ei(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Ei(l.imageSizes)+'"]')):m+='[href="'+Ei(n)+'"]';var g=m;switch(r){case"style":g=Wa(n);break;case"script":g=Ga(n)}er.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),er.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(Vl(g))||r==="script"&&u.querySelector(Xl(g))||(r=u.createElement("link"),Gi(r,"link",n),ti(r),u.head.appendChild(r)))}}function zw(n,r){Gr.m(n,r);var l=qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Ei(u)+'"][href="'+Ei(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ga(n)}if(!er.has(g)&&(n=x({rel:"modulepreload",href:n},r),er.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Xl(g)))return}u=l.createElement("link"),Gi(u,"link",n),ti(u),l.head.appendChild(u)}}}function Pw(n,r,l){Gr.S(n,r,l);var u=qa;if(u&&n){var m=Fn(u).hoistableStyles,g=Wa(n);r=r||"default";var S=m.get(g);if(!S){var k={loading:0,preload:null};if(S=u.querySelector(Vl(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Ld(n,l);var M=S=u.createElement("link");ti(M),Gi(M,"link",n),M._p=new Promise(function(V,le){M.onload=V,M.onerror=le}),M.addEventListener("load",function(){k.loading|=1}),M.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Oc(S,r,u)}S={type:"stylesheet",instance:S,count:1,state:k},m.set(g,S)}}}function Iw(n,r){Gr.X(n,r);var l=qa;if(l&&n){var u=Fn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Od(n,r),g=l.createElement("script"),ti(g),Gi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Hw(n,r){Gr.M(n,r);var l=qa;if(l&&n){var u=Fn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Od(n,r),g=l.createElement("script"),ti(g),Gi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function R_(n,r,l,u){var m=(m=oe.current)?Lc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Wa(l.href),l=Fn(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Wa(l.href);var g=Fn(m).hoistableStyles,S=g.get(n);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,S),(g=m.querySelector(Vl(n)))&&!g._p&&(S.instance=g,S.state.loading=5),er.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},er.set(n,l),g||Uw(m,n,l,S.state))),r&&u===null)throw Error(s(528,""));return S}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ga(l),l=Fn(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Wa(n){return'href="'+Ei(n)+'"'}function Vl(n){return'link[rel="stylesheet"]['+n+"]"}function M_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function Uw(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Gi(r,"link",l),ti(r),n.head.appendChild(r))}function Ga(n){return'[src="'+Ei(n)+'"]'}function Xl(n){return"script[async]"+n}function D_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Ei(l.href)+'"]');if(u)return r.instance=u,ti(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),ti(u),Gi(u,"style",m),Oc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Wa(l.href);var g=n.querySelector(Vl(m));if(g)return r.state.loading|=4,r.instance=g,ti(g),g;u=M_(l),(m=er.get(m))&&Ld(u,m),g=(n.ownerDocument||n).createElement("link"),ti(g);var S=g;return S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),Gi(g,"link",u),r.state.loading|=4,Oc(g,l.precedence,n),r.instance=g;case"script":return g=Ga(l.src),(m=n.querySelector(Xl(g)))?(r.instance=m,ti(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Od(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),ti(m),Gi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,Oc(u,l.precedence,n));return r.instance}function Oc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,S=0;S title"):null)}function $w(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function O_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Fw(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Wa(u.href),g=r.querySelector(Vl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Pc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,ti(g);return}g=r.ownerDocument||r,u=M_(u),(m=er.get(m))&&Ld(u,m),g=g.createElement("link"),ti(g);var S=g;S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),Gi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Pc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var zd=0;function qw(n,r){return n.stylesheets&&n.count===0&&Hc(n,n.stylesheets),0zd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Pc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Ic=null;function Hc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Ic=new Map,r.forEach(Ww,n),Ic=null,Pc.call(n))}function Ww(n,r){if(!(r.state.loading&4)){var l=Ic.get(n);if(l)var u=l.get(null);else{l=new Map,Ic.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Gd.exports=oC(),Gd.exports}var uC=cC();const hC=Du(uC);function dC({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const d=await e(t);d&&a(d),c(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsxs("div",{className:"w-full max-w-sm",children:[f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),f.jsxs("form",{onSubmit:h,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&f.jsx("p",{className:"text-error text-xs",children:s}),f.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),f.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function fC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),d=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsx("div",{className:"w-full max-w-sm",children:f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),f.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),f.jsxs("form",{onSubmit:d,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),f.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&f.jsx("p",{className:"text-error text-xs",children:o}),f.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const Xd="http://localhost:7777";function Sy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[d,_]=w.useState(null),x=w.useCallback((E,D)=>fetch(E,{...D,headers:{...D==null?void 0:D.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Xd}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${Xd}/api/wallet/create`,{method:"POST"}),D=await E.json();if(!E.ok)throw new Error(D.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},y=async E=>{c(E.walletId||E.name),_(null);try{const D=await x(`${Xd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),P=await D.json();if(!D.ok)throw new Error(P.error||"Wallet switch failed");b()}catch(D){_(D instanceof Error?D.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},A=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&f.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),d&&f.jsx("p",{className:"text-error text-xs",children:d}),f.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&f.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>f.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),f.jsx("button",{onClick:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),t&&t.exists&&t.address&&f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),f.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Name"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:A(t.address)}),f.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),f.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC"}),f.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"PLOT"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Network"}),f.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&f.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[f.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>f.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&f.jsx("button",{onClick:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),f.jsxs("div",{className:"border-border border-t pt-3",children:[f.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),f.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),f.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&f.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Su(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const zp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function pC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,d]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[y,N]=w.useState("AI Writer"),[A,E]=w.useState(""),[D,P]=w.useState(""),[J,q]=w.useState(!1),[L,Z]=w.useState(null),[he,ye]=w.useState(""),[U,re]=w.useState(null),[W,G]=w.useState(!1),[X,I]=w.useState(null),[j,O]=w.useState(null),[B,xe]=w.useState(null),T=w.useCallback((te,oe)=>fetch(te,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(te=>te.json()).then(te=>v(te)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(te=>te.ok?te.json():null).then(te=>{te&&xe(te)}).catch(()=>{})},[]);const R=async()=>{if(!y.trim()){Z("Agent name is required");return}if(!A.trim()){Z("Description is required");return}q(!0),Z(null);try{const te=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:y,description:A,...D.trim()&&{genre:D}})}),oe=await te.json();if(!te.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(te){Z(te instanceof Error?te.message:"Registration failed")}q(!1)},Y=async()=>{if(!he.trim()||!/^0x[a-fA-F0-9]{40}$/.test(he)){I("Enter a valid wallet address (0x...)");return}G(!0),I(null),re(null);try{const te=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:he})}),oe=await te.json();if(!te.ok)throw new Error(oe.error||"Failed to generate binding code");re(oe)}catch(te){I(te instanceof Error?te.message:"Failed to generate binding code")}G(!1)},C=async(te,oe)=>{await navigator.clipboard.writeText(te),O(oe),setTimeout(()=>O(null),2e3)},se=async()=>{if(h(null),d(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const te=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!te.ok){const oe=await te.json();throw new Error(oe.error||"Reset failed")}d(!0),s(""),o(""),setTimeout(()=>d(!1),3e3)}catch(te){h(te instanceof Error?te.message:"Reset failed")}x(!1)};return f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),f.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),f.jsx("input",{value:y,onChange:te=>N(te.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),f.jsx("input",{value:A,onChange:te=>E(te.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),f.jsx("input",{value:D,onChange:te=>P(te.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),L&&f.jsx("p",{className:"text-error text-xs",children:L}),f.jsx("button",{onClick:R,disabled:J||!y.trim()||!A.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:J?"Registering...":"Register Agent Identity"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.claude.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.codex.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),f.jsx("span",{className:"text-muted text-xs font-mono",children:(B==null?void 0:B.codex.version)??"—"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),f.jsx("span",{className:"text-muted text-xs",children:(B==null?void 0:B.codex.imageGeneration)??"unknown"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),f.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:B!=null&&B.codex.installed?B.codex.auth==="ok"?"ok":"unclear":"—"})]}),Su(B)&&f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:zp}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.checkedAt?new Date(B.checkedAt).toLocaleString():"—"})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?f.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",f.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),f.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[f.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),f.jsx("p",{children:'2. Click "Generate Binding Code"'}),f.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),f.jsx("input",{value:he,onChange:te=>ye(te.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),X&&f.jsx("p",{className:"text-error text-xs",children:X}),f.jsx("button",{onClick:Y,disabled:W||!he.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"Generating...":"Generate Binding Code"}),U&&f.jsxs("div",{className:"space-y-3 mt-3",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.signature}),f.jsx("button",{onClick:()=>C(U.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="signature"?"Copied!":"Copy"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.owsWallet}),f.jsx("button",{onClick:()=>C(U.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="wallet"?"Copied!":"Copy"})]})]}),U.agentId&&f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:U.agentId}),f.jsx("button",{onClick:()=>C(String(U.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="agentId"?"Copied!":"Copy"})]})]}),f.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),f.jsx(Sy,{token:e}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("input",{type:"password",value:i,onChange:te=>s(te.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),f.jsx("input",{type:"password",value:a,onChange:te=>o(te.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&f.jsx("p",{className:"text-error text-xs",children:c}),p&&f.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),f.jsx("button",{onClick:se,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),f.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const mC="http://localhost:7777";function gC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${mC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?f.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),f.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),f.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Active wallet"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Address"}),f.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH Balance"}),f.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC Balance"}),f.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),f.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Royalties earned"}),f.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),f.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),f.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[f.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),f.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Stories published"}),f.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?f.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):f.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>f.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[f.jsxs("div",{className:"flex items-start justify-between",children:[f.jsxs("div",{children:[h.genre&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),f.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),f.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&f.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),f.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),f.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),f.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),f.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>f.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),f.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&f.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),f.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[f.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&f.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&f.jsx("div",{className:"border-border rounded border p-4",children:f.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):f.jsx("div",{className:"flex h-full items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const xC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},_C={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function bC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,d]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),y=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const L=await q.json();h(L.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const L=await q.json();d(L.stories)}}catch{}},[e]),A=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),y())}catch{}},[e,N,y]);w.useEffect(()=>{y();const q=setInterval(y,5e3);return()=>clearInterval(q)},[y]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(L=>{const Z=new Set(L);return Z.has(q)?Z.delete(q):Z.add(q),Z})},D=q=>{var Z;const L=q.map(he=>{var ye;return{file:he.file,num:(ye=he.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(he=>he.num!=null).sort((he,ye)=>parseInt(ye.num)-parseInt(he.num));return L.length>0?L[0].file:q.some(he=>he.file==="genesis.md")?"genesis.md":q.some(he=>he.file==="structure.md")?"structure.md":((Z=q[0])==null?void 0:Z.file)??null},P=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const L=D(q.files);L&&s(q.name,L)}},J=q=>{const L=Z=>{if(Z==="structure.md")return 0;if(Z==="genesis.md")return 1;const he=Z.match(/^plot-(\d+)\.md$/);return he?2+parseInt(he[1]):100};return[...q].sort((Z,he)=>L(Z.file)-L(he.file))};return b?f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),f.jsx("span",{className:"text-xs text-muted",children:p.length})]}),f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[f.jsx("span",{children:"←"}),f.jsx("span",{children:"Back"})]})}),f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?f.jsx("div",{className:"p-3 text-sm text-muted",children:f.jsx("p",{children:"No archived stories."})}):p.map(q=>f.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[f.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),f.jsx("button",{onClick:()=>A(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),f.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[f.jsx("span",{children:"+"}),f.jsx("span",{children:"New Story"})]})}),f.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>f.jsx("div",{children:f.jsxs("button",{onClick:()=>s(q,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===q?"bg-surface":""}`,children:[f.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),f.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?f.jsxs("div",{className:"p-3 text-sm text-muted",children:[f.jsx("p",{children:"No stories yet."}),f.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>f.jsxs("div",{children:[f.jsxs("button",{onClick:()=>P(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[f.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),f.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),f.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&f.jsx("div",{className:"pl-4",children:J(q.files).map(L=>{const Z=t===q.name&&i===L.file;return f.jsxs("button",{onClick:()=>s(q.name,L.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${Z?"bg-surface font-medium":""}`,children:[f.jsx("span",{className:_C[L.status],children:xC[L.status]}),f.jsx("span",{className:"truncate font-mono",children:L.file})]},L.file)})})]},q.name))]}),f.jsx("div",{className:"px-3 py-2 border-t border-border",children:f.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:f.jsx("span",{children:"Archives"})})})]})}/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -57,22 +57,22 @@ Error generating stack: `+u.message+` * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var Sy=Object.defineProperty,xC=Object.getOwnPropertyDescriptor,bC=(e,t)=>{for(var i in t)Sy(e,i,{get:t[i],enumerable:!0})},si=(e,t,i,s)=>{for(var a=s>1?void 0:s?xC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&Sy(t,i,a),a},Me=(e,t)=>(i,s)=>t(i,s,e),sb="Terminal input",zf={get:()=>sb,set:e=>sb=e},ab="Too much output to announce, navigate to rows manually to read",Pf={get:()=>ab,set:e=>ab=e};function vC(e){return e.replace(/\r?\n/g,"\r")}function yC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function SC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function wC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");wy(a,t,i,s)}}function wy(e,t,i,s){e=vC(e),e=yC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Cy(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function lb(e,t,i,s,a){Cy(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function js(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Bu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var CC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},kC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,d=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let y=0,E;for(;(E=this.interim[++y]&63)&&y<4;)v<<=6,v|=E;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,N=A-y;for(;d=i)return 0;if(E=e[d++],(E&192)!==128){d--,b=!0;break}else this.interim[y++]=E,v<<=6,v|=E&63}b||(A===2?v<128?d--:t[s++]=v:A===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let x=i-4,_=d;for(;_=i)return this.interim[0]=a,s;if(o=e[_++],(o&192)!==128){_--;continue}if(p=(a&31)<<6|o&63,p<128){_--;continue}t[s++]=p}else if((a&240)===224){if(_>=i)return this.interim[0]=a,s;if(o=e[_++],(o&192)!==128){_--;continue}if(_>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[_++],(c&192)!==128){_--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(_>=i)return this.interim[0]=a,s;if(o=e[_++],(o&192)!==128){_--;continue}if(_>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[_++],(c&192)!==128){_--;continue}if(_>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[_++],(h&192)!==128){_--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},ky="",Rs=" ",Ao=class Ey{constructor(){this.fg=0,this.bg=0,this.extended=new wu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Ey;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},wu=class Ny{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Ny(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},ir=class Ty extends Ao{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wu,this.combinedData=""}static fromCharData(t){let i=new Ty;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?js(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ob="di$target",If="di$dependencies",Zd=new Map;function EC(e){return e[If]||[]}function Hi(e){if(Zd.has(e))return Zd.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");NC(t,i,a)};return t._id=e,Zd.set(e,t),t}function NC(e,t,i){t[ob]===t?t[If].push({id:e,index:i}):(t[If]=[{id:e,index:i}],t[ob]=t)}var hn=Hi("BufferService"),jy=Hi("CoreMouseService"),ca=Hi("CoreService"),TC=Hi("CharsetService"),Pp=Hi("InstantiationService"),Ay=Hi("LogService"),dn=Hi("OptionsService"),Ry=Hi("OscLinkService"),jC=Hi("UnicodeService"),Ro=Hi("DecorationService"),Hf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var x;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new ir,c=i.getTrimmedLength(),h=-1,p=-1,d=!1;for(let _=0;_a?a.activate(E,A,v):AC(E,A),hover:(E,A)=>{var N;return(N=a==null?void 0:a.hover)==null?void 0:N.call(a,E,A,v)},leave:(E,A)=>{var N;return(N=a==null?void 0:a.leave)==null?void 0:N.call(a,E,A,v)}})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=_,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Hf=si([Me(0,hn),Me(1,dn),Me(2,Ry)],Hf);function AC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var wy=Object.defineProperty,vC=Object.getOwnPropertyDescriptor,yC=(e,t)=>{for(var i in t)wy(e,i,{get:t[i],enumerable:!0})},oi=(e,t,i,s)=>{for(var a=s>1?void 0:s?vC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&wy(t,i,a),a},Me=(e,t)=>(i,s)=>t(i,s,e),ab="Terminal input",zf={get:()=>ab,set:e=>ab=e},lb="Too much output to announce, navigate to rows manually to read",Pf={get:()=>lb,set:e=>lb=e};function SC(e){return e.replace(/\r?\n/g,"\r")}function wC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function CC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function kC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Cy(a,t,i,s)}}function Cy(e,t,i,s){e=SC(e),e=wC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function ky(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function ob(e,t,i,s,a){ky(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function js(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Bu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var EC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},NC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,d=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let y=0,N;for(;(N=this.interim[++y]&63)&&y<4;)v<<=6,v|=N;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=A-y;for(;d=i)return 0;if(N=e[d++],(N&192)!==128){d--,b=!0;break}else this.interim[y++]=N,v<<=6,v|=N&63}b||(A===2?v<128?d--:t[s++]=v:A===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=d;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Ey="",Rs=" ",Ao=class Ny{constructor(){this.fg=0,this.bg=0,this.extended=new wu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Ny;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},wu=class Ty{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Ty(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class jy extends Ao{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wu,this.combinedData=""}static fromCharData(t){let i=new jy;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?js(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},cb="di$target",If="di$dependencies",Zd=new Map;function TC(e){return e[If]||[]}function Ui(e){if(Zd.has(e))return Zd.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");jC(t,i,a)};return t._id=e,Zd.set(e,t),t}function jC(e,t,i){t[cb]===t?t[If].push({id:e,index:i}):(t[If]=[{id:e,index:i}],t[cb]=t)}var fn=Ui("BufferService"),Ay=Ui("CoreMouseService"),ca=Ui("CoreService"),AC=Ui("CharsetService"),Pp=Ui("InstantiationService"),Ry=Ui("LogService"),pn=Ui("OptionsService"),My=Ui("OscLinkService"),RC=Ui("UnicodeService"),Ro=Ui("DecorationService"),Hf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,d=!1;for(let x=0;xa?a.activate(N,A,v):MC(N,A),hover:(N,A)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,A,v)},leave:(N,A)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,A,v)}})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Hf=oi([Me(0,fn),Me(1,pn),Me(2,My)],Hf);function MC(e,t){if(confirm(`Do you want to navigate to ${t}? -WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Lu=Hi("CharSizeService"),Qr=Hi("CoreBrowserService"),Ip=Hi("MouseService"),Jr=Hi("RenderService"),RC=Hi("SelectionService"),My=Hi("CharacterJoinerService"),cl=Hi("ThemeService"),Dy=Hi("LinkProviderService"),MC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?cb.isErrorNoTelemetry(e)?new cb(e.message+` +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Lu=Ui("CharSizeService"),Qr=Ui("CoreBrowserService"),Ip=Ui("MouseService"),Jr=Ui("RenderService"),DC=Ui("SelectionService"),Dy=Ui("CharacterJoinerService"),ol=Ui("ThemeService"),By=Ui("LinkProviderService"),BC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ub.isErrorNoTelemetry(e)?new ub(e.message+` `+e.stack):new Error(e.message+` -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},DC=new MC;function hu(e){BC(e)||DC.onUnexpectedError(e)}var Uf="Canceled";function BC(e){return e instanceof LC?!0:e instanceof Error&&e.name===Uf&&e.message===Uf}var LC=class extends Error{constructor(){super(Uf),this.name=this.message}};function OC(e){return new Error(`Illegal argument: ${e}`)}var cb=class $f extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $f)return t;let i=new $f;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ff=class By extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,By.prototype)}};function Bn(e,t=0){return e[e.length-(1+t)]}var zC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(zC||(zC={}));function PC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Ly;(e=>{function t(J){return J&&typeof J=="object"&&typeof J[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(J){yield J}e.single=a;function o(J){return t(J)?J:a(J)}e.wrap=o;function c(J){return J||i}e.from=c;function*h(J){for(let $=J.length-1;$>=0;$--)yield J[$]}e.reverse=h;function p(J){return!J||J[Symbol.iterator]().next().done===!0}e.isEmpty=p;function d(J){return J[Symbol.iterator]().next().value}e.first=d;function x(J,$){let M=0;for(let X of J)if($(X,M++))return!0;return!1}e.some=x;function _(J,$){for(let M of J)if($(M))return M}e.find=_;function*b(J,$){for(let M of J)$(M)&&(yield M)}e.filter=b;function*v(J,$){let M=0;for(let X of J)yield $(X,M++)}e.map=v;function*y(J,$){let M=0;for(let X of J)yield*$(X,M++)}e.flatMap=y;function*E(...J){for(let $ of J)yield*$}e.concat=E;function A(J,$,M){let X=M;for(let he of J)X=$(X,he);return X}e.reduce=A;function*N(J,$,M=J.length){for($<0&&($+=J.length),M<0?M+=J.length:M>J.length&&(M=J.length);$1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function IC(...e){return Qt(()=>aa(e))}function Qt(e){return{dispose:PC(()=>{e()})}}var Oy=class zy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{aa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?zy.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Oy.DISABLE_DISPOSED_WARNING=!1;var Ms=Oy,dt=class{constructor(){this._store=new Ms,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};dt.None=Object.freeze({dispose(){}});var al=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Zr=typeof window=="object"?window:globalThis,qf=class Wf{constructor(t){this.element=t,this.next=Wf.Undefined,this.prev=Wf.Undefined}};qf.Undefined=new qf(void 0);var Jt=qf,ub=class{constructor(){this._first=Jt.Undefined,this._last=Jt.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Jt.Undefined}clear(){let e=this._first;for(;e!==Jt.Undefined;){let t=e.next;e.prev=Jt.Undefined,e.next=Jt.Undefined,e=t}this._first=Jt.Undefined,this._last=Jt.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Jt(e);if(this._first===Jt.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==Jt.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Jt.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Jt.Undefined&&e.next!==Jt.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Jt.Undefined&&e.next===Jt.Undefined?(this._first=Jt.Undefined,this._last=Jt.Undefined):e.next===Jt.Undefined?(this._last=this._last.prev,this._last.next=Jt.Undefined):e.prev===Jt.Undefined&&(this._first=this._first.next,this._first.prev=Jt.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Jt.Undefined;)yield e.element,e=e.next}},HC=globalThis.performance&&typeof globalThis.performance.now=="function",UC=class Py{static create(t){return new Py(t)}constructor(t){this._now=HC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Yi;(e=>{e.None=()=>dt.None;function t(W,G){return _(W,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(W){return(G,Z=null,I)=>{let j=!1,z;return z=W(B=>{if(!j)return z?z.dispose():j=!0,G.call(Z,B)},null,I),j&&z.dispose(),z}}e.once=i;function s(W,G,Z){return d((I,j=null,z)=>W(B=>I.call(j,G(B)),null,z),Z)}e.map=s;function a(W,G,Z){return d((I,j=null,z)=>W(B=>{G(B),I.call(j,B)},null,z),Z)}e.forEach=a;function o(W,G,Z){return d((I,j=null,z)=>W(B=>G(B)&&I.call(j,B),null,z),Z)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(G,Z=null,I)=>{let j=IC(...W.map(z=>z(B=>G.call(Z,B))));return x(j,I)}}e.any=h;function p(W,G,Z,I){let j=Z;return s(W,z=>(j=G(j,z),j),I)}e.reduce=p;function d(W,G){let Z,I={onWillAddFirstListener(){Z=W(j.fire,j)},onDidRemoveLastListener(){Z==null||Z.dispose()}},j=new ke(I);return G==null||G.add(j),j.event}function x(W,G){return G instanceof Array?G.push(W):G&&G.add(W),W}function _(W,G,Z=100,I=!1,j=!1,z,B){let _e,T,R,Y=0,C,ae={leakWarningThreshold:z,onWillAddFirstListener(){_e=W(oe=>{Y++,T=G(T,oe),I&&!R&&(ie.fire(T),T=void 0),C=()=>{let F=T;T=void 0,R=void 0,(!I||Y>1)&&ie.fire(F),Y=0},typeof Z=="number"?(clearTimeout(R),R=setTimeout(C,Z)):R===void 0&&(R=0,queueMicrotask(C))})},onWillRemoveListener(){j&&Y>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,_e.dispose()}},ie=new ke(ae);return B==null||B.add(ie),ie.event}e.debounce=_;function b(W,G=0,Z){return e.debounce(W,(I,j)=>I?(I.push(j),I):[j],G,void 0,!0,void 0,Z)}e.accumulate=b;function v(W,G=(I,j)=>I===j,Z){let I=!0,j;return o(W,z=>{let B=I||!G(z,j);return I=!1,j=z,B},Z)}e.latch=v;function y(W,G,Z){return[e.filter(W,G,Z),e.filter(W,I=>!G(I),Z)]}e.split=y;function E(W,G=!1,Z=[],I){let j=Z.slice(),z=W(T=>{j?j.push(T):_e.fire(T)});I&&I.add(z);let B=()=>{j==null||j.forEach(T=>_e.fire(T)),j=null},_e=new ke({onWillAddFirstListener(){z||(z=W(T=>_e.fire(T)),I&&I.add(z))},onDidAddFirstListener(){j&&(G?setTimeout(B):B())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return I&&I.add(_e),_e.event}e.buffer=E;function A(W,G){return(Z,I,j)=>{let z=G(new L);return W(function(B){let _e=z.evaluate(B);_e!==N&&Z.call(I,_e)},void 0,j)}}e.chain=A;let N=Symbol("HaltChainable");class L{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(Z=>(G(Z),Z)),this}filter(G){return this.steps.push(Z=>G(Z)?Z:N),this}reduce(G,Z){let I=Z;return this.steps.push(j=>(I=G(I,j),I)),this}latch(G=(Z,I)=>Z===I){let Z=!0,I;return this.steps.push(j=>{let z=Z||!G(j,I);return Z=!1,I=j,z?j:N}),this}evaluate(G){for(let Z of this.steps)if(G=Z(G),G===N)break;return G}}function O(W,G,Z=I=>I){let I=(..._e)=>B.fire(Z(..._e)),j=()=>W.on(G,I),z=()=>W.removeListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:z});return B.event}e.fromNodeEventEmitter=O;function J(W,G,Z=I=>I){let I=(..._e)=>B.fire(Z(..._e)),j=()=>W.addEventListener(G,I),z=()=>W.removeEventListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:z});return B.event}e.fromDOMEventEmitter=J;function $(W){return new Promise(G=>i(W)(G))}e.toPromise=$;function M(W){let G=new ke;return W.then(Z=>{G.fire(Z)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=M;function X(W,G){return W(Z=>G.fire(Z))}e.forward=X;function he(W,G,Z){return G(Z),W(I=>G(I))}e.runAndSubscribe=he;class ye{constructor(G,Z){this._observable=G,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(I),Z&&Z.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,Z){this._hasChanged=!0}endUpdate(G){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function U(W,G){return new ye(W,G).emitter.event}e.fromObservable=U;function se(W){return(G,Z,I)=>{let j=0,z=!1,B={beginUpdate(){j++},endUpdate(){j--,j===0&&(W.reportChanges(),z&&(z=!1,G.call(Z)))},handlePossibleChange(){},handleChange(){z=!0}};W.addObserver(B),W.reportChanges();let _e={dispose(){W.removeObserver(B)}};return I instanceof Ms?I.add(_e):Array.isArray(I)&&I.push(_e),_e}}e.fromObservableLight=se})(Yi||(Yi={}));var Gf=class Yf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Yf._idPool++}`,Yf.all.add(this)}start(t){this._stopWatch=new UC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Gf.all=new Set,Gf._idPool=0;var $C=Gf,FC=-1,Iy=class Hy{constructor(t,i,s=(Hy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},LC=new BC;function hu(e){OC(e)||LC.onUnexpectedError(e)}var Uf="Canceled";function OC(e){return e instanceof zC?!0:e instanceof Error&&e.name===Uf&&e.message===Uf}var zC=class extends Error{constructor(){super(Uf),this.name=this.message}};function PC(e){return new Error(`Illegal argument: ${e}`)}var ub=class $f extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $f)return t;let i=new $f;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ff=class Ly extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Ly.prototype)}};function In(e,t=0){return e[e.length-(1+t)]}var IC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(IC||(IC={}));function HC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Oy;(e=>{function t(J){return J&&typeof J=="object"&&typeof J[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(J){yield J}e.single=a;function o(J){return t(J)?J:a(J)}e.wrap=o;function c(J){return J||i}e.from=c;function*h(J){for(let q=J.length-1;q>=0;q--)yield J[q]}e.reverse=h;function p(J){return!J||J[Symbol.iterator]().next().done===!0}e.isEmpty=p;function d(J){return J[Symbol.iterator]().next().value}e.first=d;function _(J,q){let L=0;for(let Z of J)if(q(Z,L++))return!0;return!1}e.some=_;function x(J,q){for(let L of J)if(q(L))return L}e.find=x;function*b(J,q){for(let L of J)q(L)&&(yield L)}e.filter=b;function*v(J,q){let L=0;for(let Z of J)yield q(Z,L++)}e.map=v;function*y(J,q){let L=0;for(let Z of J)yield*q(Z,L++)}e.flatMap=y;function*N(...J){for(let q of J)yield*q}e.concat=N;function A(J,q,L){let Z=L;for(let he of J)Z=q(Z,he);return Z}e.reduce=A;function*E(J,q,L=J.length){for(q<0&&(q+=J.length),L<0?L+=J.length:L>J.length&&(L=J.length);q1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function UC(...e){return Jt(()=>aa(e))}function Jt(e){return{dispose:HC(()=>{e()})}}var zy=class Py{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{aa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Py.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};zy.DISABLE_DISPOSED_WARNING=!1;var Ms=zy,ft=class{constructor(){this._store=new Ms,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ft.None=Object.freeze({dispose(){}});var sl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Zr=typeof window=="object"?window:globalThis,qf=class Wf{constructor(t){this.element=t,this.next=Wf.Undefined,this.prev=Wf.Undefined}};qf.Undefined=new qf(void 0);var ii=qf,hb=class{constructor(){this._first=ii.Undefined,this._last=ii.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ii.Undefined}clear(){let e=this._first;for(;e!==ii.Undefined;){let t=e.next;e.prev=ii.Undefined,e.next=ii.Undefined,e=t}this._first=ii.Undefined,this._last=ii.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ii(e);if(this._first===ii.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==ii.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ii.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ii.Undefined&&e.next!==ii.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ii.Undefined&&e.next===ii.Undefined?(this._first=ii.Undefined,this._last=ii.Undefined):e.next===ii.Undefined?(this._last=this._last.prev,this._last.next=ii.Undefined):e.prev===ii.Undefined&&(this._first=this._first.next,this._first.prev=ii.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ii.Undefined;)yield e.element,e=e.next}},$C=globalThis.performance&&typeof globalThis.performance.now=="function",FC=class Iy{static create(t){return new Iy(t)}constructor(t){this._now=$C&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Vi;(e=>{e.None=()=>ft.None;function t(W,G){return x(W,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(W){return(G,X=null,I)=>{let j=!1,O;return O=W(B=>{if(!j)return O?O.dispose():j=!0,G.call(X,B)},null,I),j&&O.dispose(),O}}e.once=i;function s(W,G,X){return d((I,j=null,O)=>W(B=>I.call(j,G(B)),null,O),X)}e.map=s;function a(W,G,X){return d((I,j=null,O)=>W(B=>{G(B),I.call(j,B)},null,O),X)}e.forEach=a;function o(W,G,X){return d((I,j=null,O)=>W(B=>G(B)&&I.call(j,B),null,O),X)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(G,X=null,I)=>{let j=UC(...W.map(O=>O(B=>G.call(X,B))));return _(j,I)}}e.any=h;function p(W,G,X,I){let j=X;return s(W,O=>(j=G(j,O),j),I)}e.reduce=p;function d(W,G){let X,I={onWillAddFirstListener(){X=W(j.fire,j)},onDidRemoveLastListener(){X==null||X.dispose()}},j=new ke(I);return G==null||G.add(j),j.event}function _(W,G){return G instanceof Array?G.push(W):G&&G.add(W),W}function x(W,G,X=100,I=!1,j=!1,O,B){let xe,T,R,Y=0,C,se={leakWarningThreshold:O,onWillAddFirstListener(){xe=W(oe=>{Y++,T=G(T,oe),I&&!R&&(te.fire(T),T=void 0),C=()=>{let $=T;T=void 0,R=void 0,(!I||Y>1)&&te.fire($),Y=0},typeof X=="number"?(clearTimeout(R),R=setTimeout(C,X)):R===void 0&&(R=0,queueMicrotask(C))})},onWillRemoveListener(){j&&Y>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},te=new ke(se);return B==null||B.add(te),te.event}e.debounce=x;function b(W,G=0,X){return e.debounce(W,(I,j)=>I?(I.push(j),I):[j],G,void 0,!0,void 0,X)}e.accumulate=b;function v(W,G=(I,j)=>I===j,X){let I=!0,j;return o(W,O=>{let B=I||!G(O,j);return I=!1,j=O,B},X)}e.latch=v;function y(W,G,X){return[e.filter(W,G,X),e.filter(W,I=>!G(I),X)]}e.split=y;function N(W,G=!1,X=[],I){let j=X.slice(),O=W(T=>{j?j.push(T):xe.fire(T)});I&&I.add(O);let B=()=>{j==null||j.forEach(T=>xe.fire(T)),j=null},xe=new ke({onWillAddFirstListener(){O||(O=W(T=>xe.fire(T)),I&&I.add(O))},onDidAddFirstListener(){j&&(G?setTimeout(B):B())},onDidRemoveLastListener(){O&&O.dispose(),O=null}});return I&&I.add(xe),xe.event}e.buffer=N;function A(W,G){return(X,I,j)=>{let O=G(new D);return W(function(B){let xe=O.evaluate(B);xe!==E&&X.call(I,xe)},void 0,j)}}e.chain=A;let E=Symbol("HaltChainable");class D{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(X=>(G(X),X)),this}filter(G){return this.steps.push(X=>G(X)?X:E),this}reduce(G,X){let I=X;return this.steps.push(j=>(I=G(I,j),I)),this}latch(G=(X,I)=>X===I){let X=!0,I;return this.steps.push(j=>{let O=X||!G(j,I);return X=!1,I=j,O?j:E}),this}evaluate(G){for(let X of this.steps)if(G=X(G),G===E)break;return G}}function P(W,G,X=I=>I){let I=(...xe)=>B.fire(X(...xe)),j=()=>W.on(G,I),O=()=>W.removeListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:O});return B.event}e.fromNodeEventEmitter=P;function J(W,G,X=I=>I){let I=(...xe)=>B.fire(X(...xe)),j=()=>W.addEventListener(G,I),O=()=>W.removeEventListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:O});return B.event}e.fromDOMEventEmitter=J;function q(W){return new Promise(G=>i(W)(G))}e.toPromise=q;function L(W){let G=new ke;return W.then(X=>{G.fire(X)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=L;function Z(W,G){return W(X=>G.fire(X))}e.forward=Z;function he(W,G,X){return G(X),W(I=>G(I))}e.runAndSubscribe=he;class ye{constructor(G,X){this._observable=G,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(I),X&&X.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,X){this._hasChanged=!0}endUpdate(G){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function U(W,G){return new ye(W,G).emitter.event}e.fromObservable=U;function re(W){return(G,X,I)=>{let j=0,O=!1,B={beginUpdate(){j++},endUpdate(){j--,j===0&&(W.reportChanges(),O&&(O=!1,G.call(X)))},handlePossibleChange(){},handleChange(){O=!0}};W.addObserver(B),W.reportChanges();let xe={dispose(){W.removeObserver(B)}};return I instanceof Ms?I.add(xe):Array.isArray(I)&&I.push(xe),xe}}e.fromObservableLight=re})(Vi||(Vi={}));var Gf=class Yf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Yf._idPool++}`,Yf.all.add(this)}start(t){this._stopWatch=new FC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Gf.all=new Set,Gf._idPool=0;var qC=Gf,WC=-1,Hy=class Uy{constructor(t,i,s=(Uy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{var h,p,d,x,_;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],y=new YC(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||hu)(y),dt.None}if(this._disposed)return dt.None;i&&(t=t.bind(i));let a=new Qd(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=WC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof Qd?(this._deliveryQueue??(this._deliveryQueue=new ZC),this._listeners=[this._listeners,a]):this._listeners.push(a):((d=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||d.call(p,this),this._listeners=a,(_=(x=this._options)==null?void 0:x.onDidAddFirstListener)==null||_.call(x,this)),this._size++;let c=Qt(()=>{o==null||o(),this._removeListener(a)});return s instanceof Ms?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*VC<=i.length){let d=0;for(let x=0;x0}},ZC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Kf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ke,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ke,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Kf.INSTANCE=new Kf;var Hp=Kf;function QC(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Hp.INSTANCE.onDidChangeZoomLevel;function JC(e){return Hp.INSTANCE.getZoomFactor(e)}Hp.INSTANCE.onDidChangeFullscreen;var ul=typeof navigator=="object"?navigator.userAgent:"",Vf=ul.indexOf("Firefox")>=0,ek=ul.indexOf("AppleWebKit")>=0,Up=ul.indexOf("Chrome")>=0,tk=!Up&&ul.indexOf("Safari")>=0;ul.indexOf("Electron/")>=0;ul.indexOf("Android")>=0;var Jd=!1;if(typeof Zr.matchMedia=="function"){let e=Zr.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Zr.matchMedia("(display-mode: fullscreen)");Jd=e.matches,QC(Zr,e,({matches:i})=>{Jd&&t.matches||(Jd=i)})}var il="en",Xf=!1,Zf=!1,du=!1,$y=!1,Kc,fu=il,hb=il,ik,hr,sa=globalThis,Gi,xy;typeof sa.vscode<"u"&&typeof sa.vscode.process<"u"?Gi=sa.vscode.process:typeof process<"u"&&typeof((xy=process==null?void 0:process.versions)==null?void 0:xy.node)=="string"&&(Gi=process);var by,nk=typeof((by=Gi==null?void 0:Gi.versions)==null?void 0:by.electron)=="string",rk=nk&&(Gi==null?void 0:Gi.type)==="renderer",vy;if(typeof Gi=="object"){Xf=Gi.platform==="win32",Zf=Gi.platform==="darwin",du=Gi.platform==="linux",du&&Gi.env.SNAP&&Gi.env.SNAP_REVISION,Gi.env.CI||Gi.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Kc=il,fu=il;let e=Gi.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Kc=t.userLocale,hb=t.osLocale,fu=t.resolvedLanguage||il,ik=(vy=t.languagePack)==null?void 0:vy.translationsConfigFile}catch{}$y=!0}else typeof navigator=="object"&&!rk?(hr=navigator.userAgent,Xf=hr.indexOf("Windows")>=0,Zf=hr.indexOf("Macintosh")>=0,(hr.indexOf("Macintosh")>=0||hr.indexOf("iPad")>=0||hr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,du=hr.indexOf("Linux")>=0,(hr==null?void 0:hr.indexOf("Mobi"))>=0,fu=globalThis._VSCODE_NLS_LANGUAGE||il,Kc=navigator.language.toLowerCase(),hb=Kc):console.error("Unable to resolve platform.");var Fy=Xf,Er=Zf,sk=du,db=$y,Nr=hr,ks=fu,ak;(e=>{function t(){return ks}e.value=t;function i(){return ks.length===2?ks==="en":ks.length>=3?ks[0]==="e"&&ks[1]==="n"&&ks[2]==="-":!1}e.isDefaultVariant=i;function s(){return ks==="en"}e.isDefault=s})(ak||(ak={}));var lk=typeof sa.postMessage=="function"&&!sa.importScripts;(()=>{if(lk){let e=[];sa.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),sa.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var ok=!!(Nr&&Nr.indexOf("Chrome")>=0);Nr&&Nr.indexOf("Firefox")>=0;!ok&&Nr&&Nr.indexOf("Safari")>=0;Nr&&Nr.indexOf("Edg/")>=0;Nr&&Nr.indexOf("Android")>=0;var Va=typeof navigator=="object"?navigator:{};db||document.queryCommandSupported&&document.queryCommandSupported("copy")||Va&&Va.clipboard&&Va.clipboard.writeText,db||Va&&Va.clipboard&&Va.clipboard.readText;var $p=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ef=new $p,fb=new $p,pb=new $p,ck=new Array(230),qy;(e=>{function t(h){return ef.keyCodeToStr(h)}e.toString=t;function i(h){return ef.strToKeyCode(h)}e.fromString=i;function s(h){return fb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return pb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return fb.strToKeyCode(h)||pb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return ef.keyCodeToStr(h)}e.toElectronAccelerator=c})(qy||(qy={}));var uk=class Wy{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof Wy&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new hk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},hk=class{constructor(e){if(e.length===0)throw OC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof vk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Yi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Gy})})(bk||(bk={}));var vk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Gy:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Fp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ff("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},yk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Qt(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Sk;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(Sk||(Sk={}));var xb=class Jn{static fromArray(t){return new Jn(i=>{i.emitMany(t)})}static fromPromise(t){return new Jn(async i=>{i.emitMany(await t)})}static fromPromises(t){return new Jn(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new Jn(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ke,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new Jn(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return Jn.map(this,t)}static filter(t,i){return new Jn(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return Jn.filter(this,t)}static coalesce(t){return Jn.filter(t,i=>!!i)}coalesce(){return Jn.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return Jn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};xb.EMPTY=xb.fromArray([]);var{getWindow:wr,getWindowId:wk,onDidRegisterWindow:Ck}=(function(){let e=new Map,t={window:Zr,disposables:new Ms};e.set(Zr.vscodeWindowId,t);let i=new ke,s=new ke,a=new ke;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return dt.None;let h=new Ms,p={window:c,disposables:h.add(new Ms)};return e.set(c.vscodeWindowId,p),h.add(Qt(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ye(c,Mi.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var d;let h=c;if((d=h==null?void 0:h.ownerDocument)!=null&&d.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:Zr},getDocument(c){return wr(c).document}}})(),kk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ye(e,t,i,s){return new kk(e,t,i,s)}var bb=function(e,t,i,s){return Ye(e,t,i,s)},qp,Ek=class extends yk{constructor(e){super(),this.defaultTarget=e&&wr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},vb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){hu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(vb.sort),c.shift().execute();s.set(o,!1)};qp=(o,c,h=0)=>{let p=wk(o),d=new vb(c,h),x=e.get(p);return x||(x=[],e.set(p,x)),x.push(d),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),d}})();function Nk(e){let t=e.getBoundingClientRect(),i=wr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Mi={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Tk=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=yn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=yn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=yn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=yn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=yn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=yn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=yn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=yn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=yn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=yn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=yn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=yn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=yn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=yn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function yn(e){return typeof e=="number"?`${e}px`:e}function bo(e){return new Tk(e)}var Yy=class{constructor(){this._hooks=new Ms,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(Qt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=wr(e)}this._hooks.add(Ye(o,Mi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ye(o,Mi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function jk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var yr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(yr||(yr={}));var po=class Zi extends dt{constructor(){super(),this.dispatched=!1,this.targets=new ub,this.ignoreTargets=new ub,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Yi.runAndSubscribe(Ck,({window:t,disposables:i})=>{i.add(Ye(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ye(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ye(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:Zr,disposables:this._store}))}static addTarget(t){if(!Zi.isTouchDevice())return dt.None;Zi.INSTANCE||(Zi.INSTANCE=new Zi);let i=Zi.INSTANCE.targets.push(t);return Qt(i)}static ignoreTarget(t){if(!Zi.isTouchDevice())return dt.None;Zi.INSTANCE||(Zi.INSTANCE=new Zi);let i=Zi.INSTANCE.ignoreTargets.push(t);return Qt(i)}static isTouchDevice(){return"ontouchstart"in Zr||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=Zi.HOLD_DELAY&&Math.abs(p.initialPageX-Bn(p.rollingPageX))<30&&Math.abs(p.initialPageY-Bn(p.rollingPageY))<30){let x=this.newGestureEvent(yr.Contextmenu,p.initialTarget);x.pageX=Bn(p.rollingPageX),x.pageY=Bn(p.rollingPageY),this.dispatchEvent(x)}else if(a===1){let x=Bn(p.rollingPageX),_=Bn(p.rollingPageY),b=Bn(p.rollingTimestamps)-p.rollingTimestamps[0],v=x-p.rollingPageX[0],y=_-p.rollingPageY[0],E=[...this.targets].filter(A=>p.initialTarget instanceof Node&&A.contains(p.initialTarget));this.inertia(t,E,s,Math.abs(v)/b,v>0?1:-1,x,Math.abs(y)/b,y>0?1:-1,_)}this.dispatchEvent(this.newGestureEvent(yr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===yr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>Zi.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===yr.Change||t.type===yr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,d){this.handle=qp(t,()=>{let x=Date.now(),_=x-s,b=0,v=0,y=!0;a+=Zi.SCROLL_FRICTION*_,h+=Zi.SCROLL_FRICTION*_,a>0&&(y=!1,b=o*a*_),h>0&&(y=!1,v=p*h*_);let E=this.newGestureEvent(yr.Change);E.translationX=b,E.translationY=v,i.forEach(A=>A.dispatchEvent(E)),y||this.inertia(t,i,x,a,o,c+b,h,p,d+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};po.SCROLL_FRICTION=-.005,po.HOLD_DELAY=700,po.CLEAR_TAP_COUNT_TIME=400,si([jk],po,"isTouchDevice",1);var Ak=po,Wp=class extends dt{onclick(e,t){this._register(Ye(e,Mi.CLICK,i=>t(new Vc(wr(e),i))))}onmousedown(e,t){this._register(Ye(e,Mi.MOUSE_DOWN,i=>t(new Vc(wr(e),i))))}onmouseover(e,t){this._register(Ye(e,Mi.MOUSE_OVER,i=>t(new Vc(wr(e),i))))}onmouseleave(e,t){this._register(Ye(e,Mi.MOUSE_LEAVE,i=>t(new Vc(wr(e),i))))}onkeydown(e,t){this._register(Ye(e,Mi.KEY_DOWN,i=>t(new mb(i))))}onkeyup(e,t){this._register(Ye(e,Mi.KEY_UP,i=>t(new mb(i))))}oninput(e,t){this._register(Ye(e,Mi.INPUT,t))}onblur(e,t){this._register(Ye(e,Mi.BLUR,t))}onfocus(e,t){this._register(Ye(e,Mi.FOCUS,t))}onchange(e,t){this._register(Ye(e,Mi.CHANGE,t))}ignoreGesture(e){return Ak.ignoreTarget(e)}},yb=11,Rk=class extends Wp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=yb+"px",this.domNode.style.height=yb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Yy),this._register(bb(this.bgDomNode,Mi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(bb(this.domNode,Mi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Ek),this._pointerdownScheduleRepeatTimer=this._register(new Fp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,wr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Mk=class Qf{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Qf(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qf(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Dk=class extends dt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Mk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new wb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=wb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Sb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function tf(e,t){let i=t-e;return function(s){return e+i*Ok(s)}}function Bk(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Pk=140,Ky=class extends Wp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new zk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Yy),this._shouldRender=!0,this.domNode=bo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ye(this.domNode.domNode,Mi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Rk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=bo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ye(this.slider.domNode,Mi.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=Nk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(Fy&&c>Pk){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Vy=class ep{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ep(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let d=Math.round(Math.max(20,Math.floor(s*h/a))),x=(h-d)/(a-s),_=o*x;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(d),computedSliderRatio:x,computedSliderPosition:Math.round(_)}}_refreshComputedValues(){let t=ep._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),d=Math.max(Math.min(o,h),1),x=Math.max(a,c),_=Math.max(o,h);x%p===0&&_%d===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};tp.INSTANCE=new tp;var Fk=tp,qk=class extends Wp{constructor(e,t,i){super(),this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ke),this.onWillScroll=this._onWillScroll.event,this._options=Gk(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Hk(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Ik(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=bo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=bo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=bo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Fp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=aa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Er&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new _b(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=aa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new _b(i))};this._mouseWheelToDispose.push(Ye(this._listenOnDomNode,Mi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Fk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Er&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),d={};if(o){let x=Cb*o,_=p.scrollTop-(x<0?Math.floor(x):Math.ceil(x));this._verticalScrollbar.writeScrollPosition(d,_)}if(c){let x=Cb*c,_=p.scrollLeft-(x<0?Math.floor(x):Math.ceil(x));this._horizontalScrollbar.writeScrollPosition(d,_)}d=this._scrollable.validateScrollPosition(d),(p.scrollLeft!==d.scrollLeft||p.scrollTop!==d.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(d):this._scrollable.setScrollPositionNow(d),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Uk)}},Wk=class extends qk{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Gk(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Er&&(t.className+=" mac"),t}var ip=class extends dt{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Dk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:d=>qp(s.window,d)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Wk(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(d=>{this._scrollableElement.updateOptions({handleMouseWheel:!(d&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Yi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Qt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Qt(()=>this._styleElement.remove())),this._register(Yi.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(d=>this._handleScroll(d)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ip=si([Me(2,hn),Me(3,Qr),Me(4,jy),Me(5,cl),Me(6,dn),Me(7,Jr)],ip);var np=class extends dt{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(Qt(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};np=si([Me(1,hn),Me(2,Qr),Me(3,Ro),Me(4,Jr)],np);var Yk=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},br={full:0,left:0,center:0,right:0},Es={full:0,left:0,center:0,right:0},no={full:0,left:0,center:0,right:0},Cu=class extends dt{constructor(e,t,i,s,a,o,c,h){var d;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new Yk,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(d=this._viewportElement.parentElement)==null||d.insertBefore(this._canvas,this._viewportElement),this._register(Qt(()=>{var x;return(x=this._canvas)==null?void 0:x.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Es.full=this._canvas.width,Es.left=e,Es.center=t,Es.right=e,this._refreshDrawHeightConstants(),no.full=1,no.left=1,no.center=1+Es.left,no.right=1+Es.left+Es.center}_refreshDrawHeightConstants(){br.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);br.left=t,br.center=t,br.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*br.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*br.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*br.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*br.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(no[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-br[e.position||"full"]/2),Es[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+br[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Cu=si([Me(2,hn),Me(3,Ro),Me(4,Jr),Me(5,dn),Me(6,cl),Me(7,Qr)],Cu);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var pu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(pu||(pu={}));var Xy;(e=>e.ST=`${pe.ESC}\\`)(Xy||(Xy={}));var rp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};rp=si([Me(2,hn),Me(3,dn),Me(4,ca),Me(5,Jr)],rp);var Di=0,Bi=0,Li=0,ni=0,kb={css:"#00000000",rgba:0},wi;(e=>{function t(a,o,c,h){return h!==void 0?`#${Qs(a)}${Qs(o)}${Qs(c)}${Qs(h)}`:`#${Qs(a)}${Qs(o)}${Qs(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(wi||(wi={}));var Vt;(e=>{function t(p,d){if(ni=(d.rgba&255)/255,ni===1)return{css:d.css,rgba:d.rgba};let x=d.rgba>>24&255,_=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,E=p.rgba>>8&255;Di=v+Math.round((x-v)*ni),Bi=y+Math.round((_-y)*ni),Li=E+Math.round((b-E)*ni);let A=wi.toCss(Di,Bi,Li),N=wi.toRgba(Di,Bi,Li);return{css:A,rgba:N}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,x){let _=mu.ensureContrastRatio(p.rgba,d.rgba,x);if(_)return wi.toColor(_>>24&255,_>>16&255,_>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[Di,Bi,Li]=mu.toChannels(d),{css:wi.toCss(Di,Bi,Li),rgba:d}}e.opaque=a;function o(p,d){return ni=Math.round(d*255),[Di,Bi,Li]=mu.toChannels(p.rgba),{css:wi.toCss(Di,Bi,Li,ni),rgba:wi.toRgba(Di,Bi,Li,ni)}}e.opacity=o;function c(p,d){return ni=p.rgba&255,o(p,ni*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Vt||(Vt={}));var ei;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Di=parseInt(a.slice(1,2).repeat(2),16),Bi=parseInt(a.slice(2,3).repeat(2),16),Li=parseInt(a.slice(3,4).repeat(2),16),wi.toColor(Di,Bi,Li);case 5:return Di=parseInt(a.slice(1,2).repeat(2),16),Bi=parseInt(a.slice(2,3).repeat(2),16),Li=parseInt(a.slice(3,4).repeat(2),16),ni=parseInt(a.slice(4,5).repeat(2),16),wi.toColor(Di,Bi,Li,ni);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Di=parseInt(o[1]),Bi=parseInt(o[2]),Li=parseInt(o[3]),ni=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),wi.toColor(Di,Bi,Li,ni);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Di,Bi,Li,ni]=t.getImageData(0,0,1,1).data,ni!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:wi.toRgba(Di,Bi,Li,ni),css:a}}e.toColor=s})(ei||(ei={}));var on;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),x=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),_=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+x*.7152+_*.0722}e.relativeLuminance2=i})(on||(on={}));var mu;(e=>{function t(c,h){if(ni=(h&255)/255,ni===1)return h;let p=h>>24&255,d=h>>16&255,x=h>>8&255,_=c>>24&255,b=c>>16&255,v=c>>8&255;return Di=_+Math.round((p-_)*ni),Bi=b+Math.round((d-b)*ni),Li=v+Math.round((x-v)*ni),wi.toRgba(Di,Bi,Li)}e.blend=t;function i(c,h,p){let d=on.relativeLuminance(c>>8),x=on.relativeLuminance(h>>8);if(Yr(d,x)>8));if(y>8));return y>A?v:E}return v}let _=a(c,h,p),b=Yr(d,on.relativeLuminance(_>>8));if(b>8));return b>y?_:v}return _}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,x=c>>16&255,_=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,E=Yr(on.relativeLuminance2(b,v,y),on.relativeLuminance2(d,x,_));for(;E0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),E=Yr(on.relativeLuminance2(b,v,y),on.relativeLuminance2(d,x,_));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,x=c>>16&255,_=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,E=Yr(on.relativeLuminance2(b,v,y),on.relativeLuminance2(d,x,_));for(;E>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(mu||(mu={}));function Qs(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Yr(e,t){return e1){let x=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_1){let d=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x=U,z=G,B=this._workCell;if(b.length>0&&G===b[0][0]&&j){let je=b.shift(),Ze=this._isCellInSelection(je[0],t);for(L=je[0]+1;L=je[1]),j?(I=!0,B=new Kk(this._workCell,e.translateToString(!0,je[0],je[1]),je[1]-je[0]),z=je[1]-1,Z=B.getWidth()):U=je[1]}let _e=this._isCellInSelection(G,t),T=i&&G===o,R=W&&G>=d&&G<=x,Y=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{Y=!0});let C=B.getChars()||Rs;if(C===" "&&(B.isUnderline()||B.isOverline())&&(C=" "),ye=Z*h-p.get(C,B.isBold(),B.isItalic()),!E)E=this._document.createElement("span");else if(A&&(_e&&he||!_e&&!he&&B.bg===O)&&(_e&&he&&v.selectionForeground||B.fg===J)&&B.extended.ext===$&&R===M&&ye===X&&!T&&!I&&!Y&&j){B.isInvisible()?N+=Rs:N+=C,A++;continue}else A&&(E.textContent=N),E=this._document.createElement("span"),A=0,N="";if(O=B.bg,J=B.fg,$=B.extended.ext,M=R,X=ye,he=_e,I&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(se.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&se.push("xterm-cursor-blink"),se.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":se.push("xterm-cursor-outline");break;case"block":se.push("xterm-cursor-block");break;case"bar":se.push("xterm-cursor-bar");break;case"underline":se.push("xterm-cursor-underline");break}}if(B.isBold()&&se.push("xterm-bold"),B.isItalic()&&se.push("xterm-italic"),B.isDim()&&se.push("xterm-dim"),B.isInvisible()?N=Rs:N=B.getChars()||Rs,B.isUnderline()&&(se.push(`xterm-underline-${B.extended.underlineStyle}`),N===" "&&(N=" "),!B.isUnderlineColorDefault()))if(B.isUnderlineColorRGB())E.style.textDecorationColor=`rgb(${Ao.toColorRGB(B.getUnderlineColor()).join(",")})`;else{let je=B.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&B.isBold()&&je<8&&(je+=8),E.style.textDecorationColor=v.ansi[je].css}B.isOverline()&&(se.push("xterm-overline"),N===" "&&(N=" ")),B.isStrikethrough()&&se.push("xterm-strikethrough"),R&&(E.style.textDecoration="underline");let ae=B.getFgColor(),ie=B.getFgColorMode(),oe=B.getBgColor(),F=B.getBgColorMode(),ue=!!B.isInverse();if(ue){let je=ae;ae=oe,oe=je;let Ze=ie;ie=F,F=Ze}let be,De,Ee=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{je.options.layer!=="top"&&Ee||(je.backgroundColorRGB&&(F=50331648,oe=je.backgroundColorRGB.rgba>>8&16777215,be=je.backgroundColorRGB),je.foregroundColorRGB&&(ie=50331648,ae=je.foregroundColorRGB.rgba>>8&16777215,De=je.foregroundColorRGB),Ee=je.options.layer==="top")}),!Ee&&_e&&(be=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=be.rgba>>8&16777215,F=50331648,Ee=!0,v.selectionForeground&&(ie=50331648,ae=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),Ee&&se.push("xterm-decoration-top");let Be;switch(F){case 16777216:case 33554432:Be=v.ansi[oe],se.push(`xterm-bg-${oe}`);break;case 50331648:Be=wi.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(E,`background-color:#${Eb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:ue?(Be=v.foreground,se.push("xterm-bg-257")):Be=v.background}switch(be||B.isDim()&&(be=Vt.multiplyOpacity(Be,.5)),ie){case 16777216:case 33554432:B.isBold()&&ae<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ae+=8),this._applyMinimumContrast(E,Be,v.ansi[ae],B,be,void 0)||se.push(`xterm-fg-${ae}`);break;case 50331648:let je=wi.toColor(ae>>16&255,ae>>8&255,ae&255);this._applyMinimumContrast(E,Be,je,B,be,De)||this._addStyle(E,`color:#${Eb(ae.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(E,Be,v.foreground,B,be,De)||ue&&se.push("xterm-fg-257")}se.length&&(E.className=se.join(" "),se.length=0),!T&&!I&&!Y&&j?A++:E.textContent=N,ye!==this.defaultSpacing&&(E.style.letterSpacing=`${ye}px`),_.push(E),G=z}return E&&A&&(E.textContent=N),_}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||Zk(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Vt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};sp=si([Me(1,My),Me(2,dn),Me(3,Qr),Me(4,ca),Me(5,Ro),Me(6,cl)],sp);function Eb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},e2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function t2(){return new e2}var nf="xterm-dom-renderer-owner-",Qn="xterm-rows",Zc="xterm-fg-",Nb="xterm-bg-",ro="xterm-focus",Qc="xterm-selection",i2=1,ap=class extends dt{constructor(e,t,i,s,a,o,c,h,p,d,x,_,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=d,this._bufferService=x,this._coreService=_,this._coreBrowserService=b,this._themeService=v,this._terminalClass=i2++,this._rowElements=[],this._selectionRenderModel=t2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Qn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Qc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=Qk(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(y=>this._injectCss(y))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(sp,document),this._element.classList.add(nf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(y=>this._handleLinkHover(y))),this._register(this._linkifier2.onHideLinkUnderline(y=>this._handleLinkLeave(y))),this._register(Qt(()=>{this._element.classList.remove(nf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Jk(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Qn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Qn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Qn} .xterm-dim { color: ${Vt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Qn}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Qn}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Qn}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${Qn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Qn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Qn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Qn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Qn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Qc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Qc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Qc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${Zc}${o} { color: ${c.css}; }${this._terminalSelector} .${Zc}${o}.xterm-dim { color: ${Vt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Nb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${Zc}257 { color: ${Vt.opaque(e.background).css}; }${this._terminalSelector} .${Zc}257.xterm-dim { color: ${Vt.multiplyOpacity(Vt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Nb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ro),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ro),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,d=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,d));let x=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,x)),o!==c){let _=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,_))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let d=p+i.ydisp,x=this._rowElements[p],_=i.lines.get(d);if(!x||!_)break;x.replaceChildren(...this._rowFactory.createRow(_,d,d===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${nf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,d=Math.min(h.x,a-1),x=this._optionsService.rawOptions.cursorBlink,_=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let y=v+h.ydisp,E=this._rowElements[v],A=h.lines.get(y);if(!E||!A)break;E.replaceChildren(...this._rowFactory.createRow(A,y,y===p,_,b,d,x,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};ap=si([Me(7,Pp),Me(8,Lu),Me(9,dn),Me(10,hn),Me(11,ca),Me(12,Qr),Me(13,cl)],ap);var lp=class extends dt{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ke),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new r2(this._optionsService))}catch{this._measureStrategy=this._register(new n2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lp=si([Me(2,dn)],lp);var Zy=class extends dt{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},n2=class extends Zy{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},r2=class extends Zy{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},s2=class extends dt{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new a2(this._window)),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ke),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Yi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ye(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ye(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},a2=class extends dt{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new al),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Qt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ye(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},l2=class extends dt{constructor(){super(),this.linkProviders=[],this._register(Qt(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Gp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function o2(e,t,i,s,a,o,c,h,p){if(!o)return;let d=Gp(e,t,i);if(d)return d[0]=Math.ceil((d[0]+(p?c/2:0))/c),d[1]=Math.ceil(d[1]/h),d[0]=Math.min(Math.max(d[0],1),s+(p?1:0)),d[1]=Math.min(Math.max(d[1],1),a),d}var op=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return o2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Gp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};op=si([Me(0,Jr),Me(1,Lu)],op);var c2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Qy={};bC(Qy,{getSafariVersion:()=>h2,isChromeOS:()=>i0,isFirefox:()=>Jy,isIpad:()=>d2,isIphone:()=>f2,isLegacyEdge:()=>u2,isLinux:()=>Yp,isMac:()=>Eu,isNode:()=>Ou,isSafari:()=>e0,isWindows:()=>t0});var Ou=typeof process<"u"&&"title"in process,Mo=Ou?"node":navigator.userAgent,Do=Ou?"node":navigator.platform,Jy=Mo.includes("Firefox"),u2=Mo.includes("Edge"),e0=/^((?!chrome|android).)*safari/i.test(Mo);function h2(){if(!e0)return 0;let e=Mo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Eu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Do),d2=Do==="iPad",f2=Do==="iPhone",t0=["Windows","Win16","Win32","WinCE"].includes(Do),Yp=Do.indexOf("Linux")>=0,i0=/\bCrOS\b/.test(Mo),n0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},p2=class extends n0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},m2=class extends n0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Nu=!Ou&&"requestIdleCallback"in window?m2:p2,g2=class{constructor(){this._queue=new Nu}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cp=class extends dt{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new al),this._pausedResizeTask=new g2,this._observerDisposable=this._register(new al),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ke),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ke),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ke),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new c2((d,x)=>this._renderRows(d,x),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new _2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Qt(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var d;return(d=this._renderer.value)==null?void 0:d.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(d=>this._registerIntersectionObserver(d,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Qt(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cp=si([Me(2,dn),Me(3,Lu),Me(4,ca),Me(5,Ro),Me(6,hn),Me(7,Qr),Me(8,cl)],cp);var _2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function x2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return y2(a,o,e,t,i,s)+zu(o,t,i,s)+S2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Co(Math.abs(a-e),wo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=v2(o>t?e:a,i)+(h-1)*i.cols+1+b2(o>t?a:e);return Co(p,wo(c,s))}function b2(e,t){return e-1}function v2(e,t){return t.cols-e}function y2(e,t,i,s,a,o){return zu(t,s,a,o).length===0?"":Co(s0(e,t,e,t-la(t,a),!1,a).length,wo("D",o))}function zu(e,t,i,s){let a=e-la(e,i),o=t-la(t,i),c=Math.abs(a-o)-w2(e,t,i);return Co(c,wo(r0(e,t),s))}function S2(e,t,i,s,a,o){let c;zu(t,s,a,o).length>0?c=s-la(s,a):c=t;let h=s,p=C2(e,t,i,s,a,o);return Co(s0(e,c,i,h,p==="C",a).length,wo(p,o))}function w2(e,t,i){var c;let s=0,a=e-la(e,i),o=t-la(t,i);for(let h=0;h=0&&e0?c=s-la(s,a):c=t,e=i&&ct?"A":"B"}function s0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function wo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Co(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Tb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var rf=50,E2=15,N2=50,T2=500,j2=" ",A2=new RegExp(j2,"g"),up=class extends dt{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new ir,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ke),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ke),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=d=>this._handleMouseMove(d),this._mouseUpListener=d=>this._handleMouseUp(d),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(d=>this._handleTrim(d)),this._register(this._bufferService.buffers.onBufferActivate(d=>this._handleBufferActivate(d))),this.enable(),this._model=new k2(this._bufferService),this._activeSelectionMode=0,this._register(Qt(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(d=>{d.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(A2," ")).join(t0?`\r +`))}},KC=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},VC=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},XC=0,Qd=class{constructor(e){this.value=e,this.id=XC++}},ZC=2,QC,ke=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new GC((t==null?void 0:t.onListenerError)??hu,((s=this._options)==null?void 0:s.leakWarningThreshold)??WC):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new qC(this._options._profName):void 0,this._deliveryQueue=(o=this._options)==null?void 0:o.deliveryQueue}dispose(){var t,i,s,a;this._disposed||(this._disposed=!0,((t=this._deliveryQueue)==null?void 0:t.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(s=(i=this._options)==null?void 0:i.onDidRemoveLastListener)==null||s.call(i),(a=this._leakageMon)==null||a.dispose())}get event(){return this._event??(this._event=(t,i,s)=>{var h,p,d,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],y=new VC(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||hu)(y),ft.None}if(this._disposed)return ft.None;i&&(t=t.bind(i));let a=new Qd(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=YC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof Qd?(this._deliveryQueue??(this._deliveryQueue=new JC),this._listeners=[this._listeners,a]):this._listeners.push(a):((d=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||d.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=Jt(()=>{o==null||o(),this._removeListener(a)});return s instanceof Ms?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*ZC<=i.length){let d=0;for(let _=0;_0}},JC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Kf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ke,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ke,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Kf.INSTANCE=new Kf;var Hp=Kf;function ek(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Hp.INSTANCE.onDidChangeZoomLevel;function tk(e){return Hp.INSTANCE.getZoomFactor(e)}Hp.INSTANCE.onDidChangeFullscreen;var cl=typeof navigator=="object"?navigator.userAgent:"",Vf=cl.indexOf("Firefox")>=0,ik=cl.indexOf("AppleWebKit")>=0,Up=cl.indexOf("Chrome")>=0,nk=!Up&&cl.indexOf("Safari")>=0;cl.indexOf("Electron/")>=0;cl.indexOf("Android")>=0;var Jd=!1;if(typeof Zr.matchMedia=="function"){let e=Zr.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Zr.matchMedia("(display-mode: fullscreen)");Jd=e.matches,ek(Zr,e,({matches:i})=>{Jd&&t.matches||(Jd=i)})}var tl="en",Xf=!1,Zf=!1,du=!1,Fy=!1,Kc,fu=tl,db=tl,rk,fr,sa=globalThis,Ki,by;typeof sa.vscode<"u"&&typeof sa.vscode.process<"u"?Ki=sa.vscode.process:typeof process<"u"&&typeof((by=process==null?void 0:process.versions)==null?void 0:by.node)=="string"&&(Ki=process);var vy,sk=typeof((vy=Ki==null?void 0:Ki.versions)==null?void 0:vy.electron)=="string",ak=sk&&(Ki==null?void 0:Ki.type)==="renderer",yy;if(typeof Ki=="object"){Xf=Ki.platform==="win32",Zf=Ki.platform==="darwin",du=Ki.platform==="linux",du&&Ki.env.SNAP&&Ki.env.SNAP_REVISION,Ki.env.CI||Ki.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Kc=tl,fu=tl;let e=Ki.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Kc=t.userLocale,db=t.osLocale,fu=t.resolvedLanguage||tl,rk=(yy=t.languagePack)==null?void 0:yy.translationsConfigFile}catch{}Fy=!0}else typeof navigator=="object"&&!ak?(fr=navigator.userAgent,Xf=fr.indexOf("Windows")>=0,Zf=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,du=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,fu=globalThis._VSCODE_NLS_LANGUAGE||tl,Kc=navigator.language.toLowerCase(),db=Kc):console.error("Unable to resolve platform.");var qy=Xf,Nr=Zf,lk=du,fb=Fy,Tr=fr,ks=fu,ok;(e=>{function t(){return ks}e.value=t;function i(){return ks.length===2?ks==="en":ks.length>=3?ks[0]==="e"&&ks[1]==="n"&&ks[2]==="-":!1}e.isDefaultVariant=i;function s(){return ks==="en"}e.isDefault=s})(ok||(ok={}));var ck=typeof sa.postMessage=="function"&&!sa.importScripts;(()=>{if(ck){let e=[];sa.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),sa.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var uk=!!(Tr&&Tr.indexOf("Chrome")>=0);Tr&&Tr.indexOf("Firefox")>=0;!uk&&Tr&&Tr.indexOf("Safari")>=0;Tr&&Tr.indexOf("Edg/")>=0;Tr&&Tr.indexOf("Android")>=0;var Ka=typeof navigator=="object"?navigator:{};fb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ka&&Ka.clipboard&&Ka.clipboard.writeText,fb||Ka&&Ka.clipboard&&Ka.clipboard.readText;var $p=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ef=new $p,pb=new $p,mb=new $p,hk=new Array(230),Wy;(e=>{function t(h){return ef.keyCodeToStr(h)}e.toString=t;function i(h){return ef.strToKeyCode(h)}e.fromString=i;function s(h){return pb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return mb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return pb.strToKeyCode(h)||mb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return ef.keyCodeToStr(h)}e.toElectronAccelerator=c})(Wy||(Wy={}));var dk=class Gy{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof Gy&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new fk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},fk=class{constructor(e){if(e.length===0)throw PC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof Sk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Vi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Yy})})(yk||(yk={}));var Sk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Yy:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Fp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ff("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},wk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Jt(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ck;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(Ck||(Ck={}));var bb=class ir{static fromArray(t){return new ir(i=>{i.emitMany(t)})}static fromPromise(t){return new ir(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ir(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ir(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ke,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ir(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ir.map(this,t)}static filter(t,i){return new ir(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ir.filter(this,t)}static coalesce(t){return ir.filter(t,i=>!!i)}coalesce(){return ir.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ir.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};bb.EMPTY=bb.fromArray([]);var{getWindow:Cr,getWindowId:kk,onDidRegisterWindow:Ek}=(function(){let e=new Map,t={window:Zr,disposables:new Ms};e.set(Zr.vscodeWindowId,t);let i=new ke,s=new ke,a=new ke;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ft.None;let h=new Ms,p={window:c,disposables:h.add(new Ms)};return e.set(c.vscodeWindowId,p),h.add(Jt(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ye(c,Di.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var d;let h=c;if((d=h==null?void 0:h.ownerDocument)!=null&&d.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:Zr},getDocument(c){return Cr(c).document}}})(),Nk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ye(e,t,i,s){return new Nk(e,t,i,s)}var vb=function(e,t,i,s){return Ye(e,t,i,s)},qp,Tk=class extends wk{constructor(e){super(),this.defaultTarget=e&&Cr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},yb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){hu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(yb.sort),c.shift().execute();s.set(o,!1)};qp=(o,c,h=0)=>{let p=kk(o),d=new yb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(d),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),d}})();function jk(e){let t=e.getBoundingClientRect(),i=Cr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Di={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Ak=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Cn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Cn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Cn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Cn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Cn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Cn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Cn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Cn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Cn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Cn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Cn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Cn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Cn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Cn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Cn(e){return typeof e=="number"?`${e}px`:e}function bo(e){return new Ak(e)}var Ky=class{constructor(){this._hooks=new Ms,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(Jt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Cr(e)}this._hooks.add(Ye(o,Di.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ye(o,Di.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Rk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Sr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Sr||(Sr={}));var po=class en extends ft{constructor(){super(),this.dispatched=!1,this.targets=new hb,this.ignoreTargets=new hb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Vi.runAndSubscribe(Ek,({window:t,disposables:i})=>{i.add(Ye(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ye(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ye(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:Zr,disposables:this._store}))}static addTarget(t){if(!en.isTouchDevice())return ft.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.targets.push(t);return Jt(i)}static ignoreTarget(t){if(!en.isTouchDevice())return ft.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.ignoreTargets.push(t);return Jt(i)}static isTouchDevice(){return"ontouchstart"in Zr||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=en.HOLD_DELAY&&Math.abs(p.initialPageX-In(p.rollingPageX))<30&&Math.abs(p.initialPageY-In(p.rollingPageY))<30){let _=this.newGestureEvent(Sr.Contextmenu,p.initialTarget);_.pageX=In(p.rollingPageX),_.pageY=In(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=In(p.rollingPageX),x=In(p.rollingPageY),b=In(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],y=x-p.rollingPageY[0],N=[...this.targets].filter(A=>p.initialTarget instanceof Node&&A.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(y)/b,y>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Sr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Sr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>en.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Sr.Change||t.type===Sr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,d){this.handle=qp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,y=!0;a+=en.SCROLL_FRICTION*x,h+=en.SCROLL_FRICTION*x,a>0&&(y=!1,b=o*a*x),h>0&&(y=!1,v=p*h*x);let N=this.newGestureEvent(Sr.Change);N.translationX=b,N.translationY=v,i.forEach(A=>A.dispatchEvent(N)),y||this.inertia(t,i,_,a,o,c+b,h,p,d+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};po.SCROLL_FRICTION=-.005,po.HOLD_DELAY=700,po.CLEAR_TAP_COUNT_TIME=400,oi([Rk],po,"isTouchDevice",1);var Mk=po,Wp=class extends ft{onclick(e,t){this._register(Ye(e,Di.CLICK,i=>t(new Vc(Cr(e),i))))}onmousedown(e,t){this._register(Ye(e,Di.MOUSE_DOWN,i=>t(new Vc(Cr(e),i))))}onmouseover(e,t){this._register(Ye(e,Di.MOUSE_OVER,i=>t(new Vc(Cr(e),i))))}onmouseleave(e,t){this._register(Ye(e,Di.MOUSE_LEAVE,i=>t(new Vc(Cr(e),i))))}onkeydown(e,t){this._register(Ye(e,Di.KEY_DOWN,i=>t(new gb(i))))}onkeyup(e,t){this._register(Ye(e,Di.KEY_UP,i=>t(new gb(i))))}oninput(e,t){this._register(Ye(e,Di.INPUT,t))}onblur(e,t){this._register(Ye(e,Di.BLUR,t))}onfocus(e,t){this._register(Ye(e,Di.FOCUS,t))}onchange(e,t){this._register(Ye(e,Di.CHANGE,t))}ignoreGesture(e){return Mk.ignoreTarget(e)}},Sb=11,Dk=class extends Wp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Sb+"px",this.domNode.style.height=Sb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ky),this._register(vb(this.bgDomNode,Di.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(vb(this.domNode,Di.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Tk),this._pointerdownScheduleRepeatTimer=this._register(new Fp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Cr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Bk=class Qf{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Qf(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qf(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Lk=class extends ft{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Bk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Cb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Cb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},wb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function tf(e,t){let i=t-e;return function(s){return e+i*Pk(s)}}function Ok(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Hk=140,Vy=class extends Wp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Ik(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ky),this._shouldRender=!0,this.domNode=bo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ye(this.domNode.domNode,Di.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Dk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=bo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ye(this.slider.domNode,Di.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=jk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(qy&&c>Hk){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Xy=class ep{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ep(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let d=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-d)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(d),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=ep._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),d=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%d===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};tp.INSTANCE=new tp;var Wk=tp,Gk=class extends Wp{constructor(e,t,i){super(),this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ke),this.onWillScroll=this._onWillScroll.event,this._options=Kk(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new $k(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Uk(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=bo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=bo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=bo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Fp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=aa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Nr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new _b(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=aa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new _b(i))};this._mouseWheelToDispose.push(Ye(this._listenOnDomNode,Di.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Wk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Nr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),d={};if(o){let _=kb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(d,x)}if(c){let _=kb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(d,x)}d=this._scrollable.validateScrollPosition(d),(p.scrollLeft!==d.scrollLeft||p.scrollTop!==d.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(d):this._scrollable.setScrollPositionNow(d),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Fk)}},Yk=class extends Gk{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Kk(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Nr&&(t.className+=" mac"),t}var ip=class extends ft{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Lk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:d=>qp(s.window,d)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Yk(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(d=>{this._scrollableElement.updateOptions({handleMouseWheel:!(d&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Vi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Jt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Jt(()=>this._styleElement.remove())),this._register(Vi.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(d=>this._handleScroll(d)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ip=oi([Me(2,fn),Me(3,Qr),Me(4,Ay),Me(5,ol),Me(6,pn),Me(7,Jr)],ip);var np=class extends ft{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(Jt(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};np=oi([Me(1,fn),Me(2,Qr),Me(3,Ro),Me(4,Jr)],np);var Vk=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},vr={full:0,left:0,center:0,right:0},Es={full:0,left:0,center:0,right:0},no={full:0,left:0,center:0,right:0},Cu=class extends ft{constructor(e,t,i,s,a,o,c,h){var d;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new Vk,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(d=this._viewportElement.parentElement)==null||d.insertBefore(this._canvas,this._viewportElement),this._register(Jt(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Es.full=this._canvas.width,Es.left=e,Es.center=t,Es.right=e,this._refreshDrawHeightConstants(),no.full=1,no.left=1,no.center=1+Es.left,no.right=1+Es.left+Es.center}_refreshDrawHeightConstants(){vr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);vr.left=t,vr.center=t,vr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(no[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-vr[e.position||"full"]/2),Es[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+vr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Cu=oi([Me(2,fn),Me(3,Ro),Me(4,Jr),Me(5,pn),Me(6,ol),Me(7,Qr)],Cu);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var pu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(pu||(pu={}));var Zy;(e=>e.ST=`${pe.ESC}\\`)(Zy||(Zy={}));var rp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};rp=oi([Me(2,fn),Me(3,pn),Me(4,ca),Me(5,Jr)],rp);var Bi=0,Li=0,Oi=0,ai=0,Eb={css:"#00000000",rgba:0},Ci;(e=>{function t(a,o,c,h){return h!==void 0?`#${Qs(a)}${Qs(o)}${Qs(c)}${Qs(h)}`:`#${Qs(a)}${Qs(o)}${Qs(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(Ci||(Ci={}));var Xt;(e=>{function t(p,d){if(ai=(d.rgba&255)/255,ai===1)return{css:d.css,rgba:d.rgba};let _=d.rgba>>24&255,x=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,N=p.rgba>>8&255;Bi=v+Math.round((_-v)*ai),Li=y+Math.round((x-y)*ai),Oi=N+Math.round((b-N)*ai);let A=Ci.toCss(Bi,Li,Oi),E=Ci.toRgba(Bi,Li,Oi);return{css:A,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,_){let x=mu.ensureContrastRatio(p.rgba,d.rgba,_);if(x)return Ci.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[Bi,Li,Oi]=mu.toChannels(d),{css:Ci.toCss(Bi,Li,Oi),rgba:d}}e.opaque=a;function o(p,d){return ai=Math.round(d*255),[Bi,Li,Oi]=mu.toChannels(p.rgba),{css:Ci.toCss(Bi,Li,Oi,ai),rgba:Ci.toRgba(Bi,Li,Oi,ai)}}e.opacity=o;function c(p,d){return ai=p.rgba&255,o(p,ai*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Xt||(Xt={}));var ni;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Bi=parseInt(a.slice(1,2).repeat(2),16),Li=parseInt(a.slice(2,3).repeat(2),16),Oi=parseInt(a.slice(3,4).repeat(2),16),Ci.toColor(Bi,Li,Oi);case 5:return Bi=parseInt(a.slice(1,2).repeat(2),16),Li=parseInt(a.slice(2,3).repeat(2),16),Oi=parseInt(a.slice(3,4).repeat(2),16),ai=parseInt(a.slice(4,5).repeat(2),16),Ci.toColor(Bi,Li,Oi,ai);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Bi=parseInt(o[1]),Li=parseInt(o[2]),Oi=parseInt(o[3]),ai=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ci.toColor(Bi,Li,Oi,ai);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Bi,Li,Oi,ai]=t.getImageData(0,0,1,1).data,ai!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ci.toRgba(Bi,Li,Oi,ai),css:a}}e.toColor=s})(ni||(ni={}));var un;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(un||(un={}));var mu;(e=>{function t(c,h){if(ai=(h&255)/255,ai===1)return h;let p=h>>24&255,d=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Bi=x+Math.round((p-x)*ai),Li=b+Math.round((d-b)*ai),Oi=v+Math.round((_-v)*ai),Ci.toRgba(Bi,Li,Oi)}e.blend=t;function i(c,h,p){let d=un.relativeLuminance(c>>8),_=un.relativeLuminance(h>>8);if(Yr(d,_)>8));if(y>8));return y>A?v:N}return v}let x=a(c,h,p),b=Yr(d,un.relativeLuminance(x>>8));if(b>8));return b>y?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(mu||(mu={}));function Qs(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Yr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=d,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Rs.length}if(this._bufferService.cols-a>1){let d=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=U,O=G,B=this._workCell;if(b.length>0&&G===b[0][0]&&j){let je=b.shift(),Ze=this._isCellInSelection(je[0],t);for(D=je[0]+1;D=je[1]),j?(I=!0,B=new Xk(this._workCell,e.translateToString(!0,je[0],je[1]),je[1]-je[0]),O=je[1]-1,X=B.getWidth()):U=je[1]}let xe=this._isCellInSelection(G,t),T=i&&G===o,R=W&&G>=d&&G<=_,Y=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{Y=!0});let C=B.getChars()||Rs;if(C===" "&&(B.isUnderline()||B.isOverline())&&(C=" "),ye=X*h-p.get(C,B.isBold(),B.isItalic()),!N)N=this._document.createElement("span");else if(A&&(xe&&he||!xe&&!he&&B.bg===P)&&(xe&&he&&v.selectionForeground||B.fg===J)&&B.extended.ext===q&&R===L&&ye===Z&&!T&&!I&&!Y&&j){B.isInvisible()?E+=Rs:E+=C,A++;continue}else A&&(N.textContent=E),N=this._document.createElement("span"),A=0,E="";if(P=B.bg,J=B.fg,q=B.extended.ext,L=R,Z=ye,he=xe,I&&o>=G&&o<=O&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(re.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&re.push("xterm-cursor-blink"),re.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":re.push("xterm-cursor-outline");break;case"block":re.push("xterm-cursor-block");break;case"bar":re.push("xterm-cursor-bar");break;case"underline":re.push("xterm-cursor-underline");break}}if(B.isBold()&&re.push("xterm-bold"),B.isItalic()&&re.push("xterm-italic"),B.isDim()&&re.push("xterm-dim"),B.isInvisible()?E=Rs:E=B.getChars()||Rs,B.isUnderline()&&(re.push(`xterm-underline-${B.extended.underlineStyle}`),E===" "&&(E=" "),!B.isUnderlineColorDefault()))if(B.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Ao.toColorRGB(B.getUnderlineColor()).join(",")})`;else{let je=B.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&B.isBold()&&je<8&&(je+=8),N.style.textDecorationColor=v.ansi[je].css}B.isOverline()&&(re.push("xterm-overline"),E===" "&&(E=" ")),B.isStrikethrough()&&re.push("xterm-strikethrough"),R&&(N.style.textDecoration="underline");let se=B.getFgColor(),te=B.getFgColorMode(),oe=B.getBgColor(),$=B.getBgColorMode(),ue=!!B.isInverse();if(ue){let je=se;se=oe,oe=je;let Ze=te;te=$,$=Ze}let be,De,Ee=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{je.options.layer!=="top"&&Ee||(je.backgroundColorRGB&&($=50331648,oe=je.backgroundColorRGB.rgba>>8&16777215,be=je.backgroundColorRGB),je.foregroundColorRGB&&(te=50331648,se=je.foregroundColorRGB.rgba>>8&16777215,De=je.foregroundColorRGB),Ee=je.options.layer==="top")}),!Ee&&xe&&(be=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=be.rgba>>8&16777215,$=50331648,Ee=!0,v.selectionForeground&&(te=50331648,se=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),Ee&&re.push("xterm-decoration-top");let Be;switch($){case 16777216:case 33554432:Be=v.ansi[oe],re.push(`xterm-bg-${oe}`);break;case 50331648:Be=Ci.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Nb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:ue?(Be=v.foreground,re.push("xterm-bg-257")):Be=v.background}switch(be||B.isDim()&&(be=Xt.multiplyOpacity(Be,.5)),te){case 16777216:case 33554432:B.isBold()&&se<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(se+=8),this._applyMinimumContrast(N,Be,v.ansi[se],B,be,void 0)||re.push(`xterm-fg-${se}`);break;case 50331648:let je=Ci.toColor(se>>16&255,se>>8&255,se&255);this._applyMinimumContrast(N,Be,je,B,be,De)||this._addStyle(N,`color:#${Nb(se.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Be,v.foreground,B,be,De)||ue&&re.push("xterm-fg-257")}re.length&&(N.className=re.join(" "),re.length=0),!T&&!I&&!Y&&j?A++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=O}return N&&A&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||Jk(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Xt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};sp=oi([Me(1,Dy),Me(2,pn),Me(3,Qr),Me(4,ca),Me(5,Ro),Me(6,ol)],sp);function Nb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},i2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function n2(){return new i2}var nf="xterm-dom-renderer-owner-",tr="xterm-rows",Zc="xterm-fg-",Tb="xterm-bg-",ro="xterm-focus",Qc="xterm-selection",r2=1,ap=class extends ft{constructor(e,t,i,s,a,o,c,h,p,d,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=d,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=r2++,this._rowElements=[],this._selectionRenderModel=n2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(tr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Qc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=e2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(y=>this._injectCss(y))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(sp,document),this._element.classList.add(nf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(y=>this._handleLinkHover(y))),this._register(this._linkifier2.onHideLinkUnderline(y=>this._handleLinkLeave(y))),this._register(Jt(()=>{this._element.classList.remove(nf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new t2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tr} .xterm-dim { color: ${Xt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Qc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Qc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Qc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${Zc}${o} { color: ${c.css}; }${this._terminalSelector} .${Zc}${o}.xterm-dim { color: ${Xt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Tb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${Zc}257 { color: ${Xt.opaque(e.background).css}; }${this._terminalSelector} .${Zc}257.xterm-dim { color: ${Xt.multiplyOpacity(Xt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Tb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ro),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ro),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,d=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,d));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let d=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(d);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,d,d===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${nf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,d=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let y=v+h.ydisp,N=this._rowElements[v],A=h.lines.get(y);if(!N||!A)break;N.replaceChildren(...this._rowFactory.createRow(A,y,y===p,x,b,d,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};ap=oi([Me(7,Pp),Me(8,Lu),Me(9,pn),Me(10,fn),Me(11,ca),Me(12,Qr),Me(13,ol)],ap);var lp=class extends ft{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ke),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new a2(this._optionsService))}catch{this._measureStrategy=this._register(new s2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lp=oi([Me(2,pn)],lp);var Qy=class extends ft{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},s2=class extends Qy{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},a2=class extends Qy{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},l2=class extends ft{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new o2(this._window)),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ke),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Vi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ye(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ye(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},o2=class extends ft{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new sl),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Jt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ye(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},c2=class extends ft{constructor(){super(),this.linkProviders=[],this._register(Jt(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Gp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function u2(e,t,i,s,a,o,c,h,p){if(!o)return;let d=Gp(e,t,i);if(d)return d[0]=Math.ceil((d[0]+(p?c/2:0))/c),d[1]=Math.ceil(d[1]/h),d[0]=Math.min(Math.max(d[0],1),s+(p?1:0)),d[1]=Math.min(Math.max(d[1],1),a),d}var op=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return u2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Gp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};op=oi([Me(0,Jr),Me(1,Lu)],op);var h2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Jy={};yC(Jy,{getSafariVersion:()=>f2,isChromeOS:()=>n0,isFirefox:()=>e0,isIpad:()=>p2,isIphone:()=>m2,isLegacyEdge:()=>d2,isLinux:()=>Yp,isMac:()=>Eu,isNode:()=>Ou,isSafari:()=>t0,isWindows:()=>i0});var Ou=typeof process<"u"&&"title"in process,Mo=Ou?"node":navigator.userAgent,Do=Ou?"node":navigator.platform,e0=Mo.includes("Firefox"),d2=Mo.includes("Edge"),t0=/^((?!chrome|android).)*safari/i.test(Mo);function f2(){if(!t0)return 0;let e=Mo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Eu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Do),p2=Do==="iPad",m2=Do==="iPhone",i0=["Windows","Win16","Win32","WinCE"].includes(Do),Yp=Do.indexOf("Linux")>=0,n0=/\bCrOS\b/.test(Mo),r0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},g2=class extends r0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},x2=class extends r0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Nu=!Ou&&"requestIdleCallback"in window?x2:g2,_2=class{constructor(){this._queue=new Nu}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cp=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new sl),this._pausedResizeTask=new _2,this._observerDisposable=this._register(new sl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ke),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ke),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ke),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new h2((d,_)=>this._renderRows(d,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new b2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Jt(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var d;return(d=this._renderer.value)==null?void 0:d.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(d=>this._registerIntersectionObserver(d,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Jt(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cp=oi([Me(2,pn),Me(3,Lu),Me(4,ca),Me(5,Ro),Me(6,fn),Me(7,Qr),Me(8,ol)],cp);var b2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function v2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return w2(a,o,e,t,i,s)+zu(o,t,i,s)+C2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Co(Math.abs(a-e),wo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=S2(o>t?e:a,i)+(h-1)*i.cols+1+y2(o>t?a:e);return Co(p,wo(c,s))}function y2(e,t){return e-1}function S2(e,t){return t.cols-e}function w2(e,t,i,s,a,o){return zu(t,s,a,o).length===0?"":Co(a0(e,t,e,t-la(t,a),!1,a).length,wo("D",o))}function zu(e,t,i,s){let a=e-la(e,i),o=t-la(t,i),c=Math.abs(a-o)-k2(e,t,i);return Co(c,wo(s0(e,t),s))}function C2(e,t,i,s,a,o){let c;zu(t,s,a,o).length>0?c=s-la(s,a):c=t;let h=s,p=E2(e,t,i,s,a,o);return Co(a0(e,c,i,h,p==="C",a).length,wo(p,o))}function k2(e,t,i){var c;let s=0,a=e-la(e,i),o=t-la(t,i);for(let h=0;h=0&&e0?c=s-la(s,a):c=t,e=i&&ct?"A":"B"}function a0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function wo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Co(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function jb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var rf=50,T2=15,j2=50,A2=500,R2=" ",M2=new RegExp(R2,"g"),up=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ke),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ke),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=d=>this._handleMouseMove(d),this._mouseUpListener=d=>this._handleMouseUp(d),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(d=>this._handleTrim(d)),this._register(this._bufferService.buffers.onBufferActivate(d=>this._handleBufferActivate(d))),this.enable(),this._model=new N2(this._bufferService),this._activeSelectionMode=0,this._register(Jt(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(d=>{d.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(M2," ")).join(i0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Yp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Tb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Gp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-rf),rf),t/=rf,t/Math.abs(t)+Math.round(t*(E2-1)))}shouldForceSelection(e){return Eu?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),N2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Eu&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,d=e[0]-h,x=0,_=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=L-1,p+=L-1);A>0&&h>0&&!this._isCharWordSeparator(o.loadCell(A-1,this._workCell));){o.loadCell(A-1,this._workCell);let O=this._workCell.getChars().length;this._workCell.getWidth()===0?(x++,A--):O>1&&(b+=O-1,h-=O-1),h--,A--}for(;N1&&(v+=O-1,p+=O-1),p++,N++}}p++;let y=h+d-x+b,E=Math.min(this._bufferService.cols,p-h+x+_-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&y===0&&o.getCodePoint(0)!==32){let A=a.lines.get(e[1]-1);if(A&&o.isWrapped&&A.getCodePoint(this._bufferService.cols-1)!==32){let N=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(N){let L=this._bufferService.cols-N.start;y-=L,E+=L}}}if(s&&y+E===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let A=a.lines.get(e[1]+1);if(A!=null&&A.isWrapped&&A.getCodePoint(0)!==32){let N=this._getWordAt([0,e[1]+1],!1,!1,!0);N&&(E+=N.length)}}return{start:y,length:E}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Tb(i,this._bufferService.cols)}};up=si([Me(3,hn),Me(4,ca),Me(5,Ip),Me(6,dn),Me(7,Jr),Me(8,Qr)],up);var jb=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Ab=class{constructor(){this._color=new jb,this._css=new jb}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ni=Object.freeze((()=>{let e=[ei.toColor("#2e3436"),ei.toColor("#cc0000"),ei.toColor("#4e9a06"),ei.toColor("#c4a000"),ei.toColor("#3465a4"),ei.toColor("#75507b"),ei.toColor("#06989a"),ei.toColor("#d3d7cf"),ei.toColor("#555753"),ei.toColor("#ef2929"),ei.toColor("#8ae234"),ei.toColor("#fce94f"),ei.toColor("#729fcf"),ei.toColor("#ad7fa8"),ei.toColor("#34e2e2"),ei.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:wi.toCss(s,a,o),rgba:wi.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:wi.toCss(s,s,s),rgba:wi.toRgba(s,s,s)})}return e})()),ia=ei.toColor("#ffffff"),mo=ei.toColor("#000000"),Rb=ei.toColor("#ffffff"),Mb=mo,so={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},R2=ia,hp=class extends dt{constructor(e){super(),this._optionsService=e,this._contrastCache=new Ab,this._halfContrastCache=new Ab,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ia,background:mo,cursor:Rb,cursorAccent:Mb,selectionForeground:void 0,selectionBackgroundTransparent:so,selectionBackgroundOpaque:Vt.blend(mo,so),selectionInactiveBackgroundTransparent:so,selectionInactiveBackgroundOpaque:Vt.blend(mo,so),scrollbarSliderBackground:Vt.opacity(ia,.2),scrollbarSliderHoverBackground:Vt.opacity(ia,.4),scrollbarSliderActiveBackground:Vt.opacity(ia,.5),overviewRulerBorder:ia,ansi:Ni.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Ut(e.foreground,ia),t.background=Ut(e.background,mo),t.cursor=Vt.blend(t.background,Ut(e.cursor,Rb)),t.cursorAccent=Vt.blend(t.background,Ut(e.cursorAccent,Mb)),t.selectionBackgroundTransparent=Ut(e.selectionBackground,so),t.selectionBackgroundOpaque=Vt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Ut(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Vt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Ut(e.selectionForeground,kb):void 0,t.selectionForeground===kb&&(t.selectionForeground=void 0),Vt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Vt.opacity(t.selectionBackgroundTransparent,.3)),Vt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Vt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Ut(e.scrollbarSliderBackground,Vt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Ut(e.scrollbarSliderHoverBackground,Vt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Ut(e.scrollbarSliderActiveBackground,Vt.opacity(t.foreground,.5)),t.overviewRulerBorder=Ut(e.overviewRulerBorder,R2),t.ansi=Ni.slice(),t.ansi[0]=Ut(e.black,Ni[0]),t.ansi[1]=Ut(e.red,Ni[1]),t.ansi[2]=Ut(e.green,Ni[2]),t.ansi[3]=Ut(e.yellow,Ni[3]),t.ansi[4]=Ut(e.blue,Ni[4]),t.ansi[5]=Ut(e.magenta,Ni[5]),t.ansi[6]=Ut(e.cyan,Ni[6]),t.ansi[7]=Ut(e.white,Ni[7]),t.ansi[8]=Ut(e.brightBlack,Ni[8]),t.ansi[9]=Ut(e.brightRed,Ni[9]),t.ansi[10]=Ut(e.brightGreen,Ni[10]),t.ansi[11]=Ut(e.brightYellow,Ni[11]),t.ansi[12]=Ut(e.brightBlue,Ni[12]),t.ansi[13]=Ut(e.brightMagenta,Ni[13]),t.ansi[14]=Ut(e.brightCyan,Ni[14]),t.ansi[15]=Ut(e.brightWhite,Ni[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},B2={trace:0,debug:1,info:2,warn:3,error:4,off:5},L2="xterm.js: ",dp=class extends dt{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=B2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*ht+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ht+0]=t|2097152|i[2]<<22):this._data[t*ht+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ht+0]>>22}hasWidth(t){return this._data[t*ht+0]&12582912}getFg(t){return this._data[t*ht+1]}getBg(t){return this._data[t*ht+2]}hasContent(t){return this._data[t*ht+0]&4194303}getCodePoint(t){let i=this._data[t*ht+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ht+0]&2097152}getString(t){let i=this._data[t*ht+0];return i&2097152?this._combined[t]:i&2097151?js(i&2097151):""}isProtected(t){return this._data[t*ht+2]&536870912}loadCell(t,i){return Jc=t*ht,i.content=this._data[Jc+0],i.fg=this._data[Jc+1],i.bg=this._data[Jc+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ht+0]=i.content,this._data[t*ht+1]=i.fg,this._data[t*ht+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ht+0]=i|s<<22,this._data[t*ht+1]=a.fg,this._data[t*ht+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ht+0];a&2097152?this._combined[t]+=js(i):a&2097151?(this._combined[t]=js(a&2097151)+js(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ht+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*sf=0;--t)if(this._data[t*ht+0]&4194303)return t+(this._data[t*ht+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ht+0]&4194303||this._data[t*ht+2]&50331648)return t+(this._data[t*ht+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let d=0;d=i&&(this._combined[d-i+s]=t._combined[d])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function O2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(A>_||x[A].getTrimmedLength()===0);A--)E++;E>0&&(c.push(h+x.length-E),c.push(E)),h+=x.length-1}return c}function z2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cko(e,d,t)).reduce((p,d)=>p+d),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let d=e[c].getWidth(o-1)===2;d&&o--;let x=d?i-1:i;s.push(x),h+=x}return s}function ko(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var l0=class o0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=o0._nextId++,this._onDispose=this.register(new ke),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),aa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};l0._nextId=1;var H2=l0,Ai={},na=Ai.B;Ai[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Ai.A={"#":"£"};Ai.B=void 0;Ai[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Ai.C=Ai[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ai.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Ai.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Ai.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Ai.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Ai.E=Ai[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Ai.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Ai.H=Ai[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ai["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Bb=4294967295,Lb=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Si.clone(),this.savedCharset=na,this.markers=[],this._nullCell=ir.fromCharData([0,ky,1,0]),this._whitespaceCell=ir.fromCharData([0,Rs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Nu,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Db(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new wu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new wu),this._whitespaceCell}getBlankLine(e,t){return new go(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eBb?Bb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Si);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Db(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Si),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new go(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=O2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Si),i);if(s.length>0){let a=z2(this.lines,s);P2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Si),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let O=this.ybase+this.y;if(O>=c&&O0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let y=x.length-1,E=x[y];E===0&&(y--,E=x[y]);let A=p.length-_-1,N=d;for(;A>=0;){let O=Math.min(N,E);if(p[y]===void 0)break;if(p[y].copyCellsFrom(p[A],N-O,E-O,O,!0),E-=O,E===0&&(y--,E=x[y]),N-=O,N===0){A--;let J=Math.max(A,0);N=ko(p,J,this._cols)}}for(let O=0;O0;)this.ybase===0?this.y0){let c=[],h=[];for(let E=0;E=0;E--)if(_&&_.start>d+b){for(let A=_.newLines.length-1;A>=0;A--)this.lines.set(E--,_.newLines[A]);E++,c.push({index:d+1,amount:_.newLines.length}),b+=_.newLines.length,_=a[++x]}else this.lines.set(E,h[d--]);let v=0;for(let E=c.length-1;E>=0;E--)c[E].index+=v,this.lines.onInsertEmitter.fire(c[E]),v+=c[E].amount;let y=Math.max(0,p+o-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},U2=class extends dt{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ke),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Lb(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Lb(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},c0=2,u0=1,fp=class extends dt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,c0),this.rows=Math.max(e.rawOptions.rows||0,u0),this.buffers=this._register(new U2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};fp=si([Me(0,dn)],fp);var Xa={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Eu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},$2=["normal","bold","100","200","300","400","500","600","700","800","900"],F2=class extends dt{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...Xa};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Qt(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Xa))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Xa))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Xa[e]),!q2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Xa[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=$2.includes(t)?t:Xa[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function q2(e){return e==="block"||e==="underline"||e==="bar"}function _o(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&_o(e[s],t-1);return i}var Ob=Object.freeze({insertMode:!1}),zb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pp=class extends dt{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ke),this.onData=this._onData.event,this._onUserInput=this._register(new ke),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ke),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=_o(Ob),this.decPrivateModes=_o(zb)}reset(){this.modes=_o(Ob),this.decPrivateModes=_o(zb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pp=si([Me(0,hn),Me(1,Ay),Me(2,dn)],pp);var Pb={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function af(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var lf=String.fromCharCode,Ib={DEFAULT:e=>{let t=[af(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${lf(t[0])}${lf(t[1])}${lf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.x};${e.y}${t}`}},mp=class extends dt{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ke),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Pb))this.addProtocol(s,Pb[s]);for(let s of Object.keys(Ib))this.addEncoding(s,Ib[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mp=si([Me(0,hn),Me(1,ca),Me(2,dn)],mp);var of=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],W2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Ti;function G2(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ra.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ra.createPropertyValue(0,i,s)}},ra=class gu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new Y2;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let d=t.charCodeAt(o);56320<=d&&d<=57343?c=(c-55296)*1024+d-56320+65536:i+=this.wcwidth(d)}let h=this.charProperties(c,s),p=gu.extractWidth(h);gu.extractShouldJoin(h)&&(p-=gu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},K2=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Hb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ao=2147483647,V2=256,h0=class gp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>V2)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new gp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ao?ao:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>ao?ao:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,ao):t}},lo=[],X2=class{constructor(){this._state=0,this._active=lo,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=lo}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=lo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lo,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=lo,this._id=-1,this._state=0}}},Ln=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},oo=[],Z2=class{constructor(){this._handlers=Object.create(null),this._active=oo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=oo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=oo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||oo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=oo,this._ident=0}},xo=new h0;xo.addParam(0);var Ub=class{constructor(e){this._handler=e,this._data="",this._params=xo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():xo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=xo,this._data="",this._hitLimit=!1,i));return this._params=xo,this._data="",this._hitLimit=!1,t}},Q2=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(er,0,2,0),e.add(er,8,5,8),e.add(er,6,0,6),e.add(er,11,0,11),e.add(er,13,13,13),e})(),eE=class extends dt{constructor(e=J2){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new h0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Qt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new X2),this._dcsParser=this._register(new Z2),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[d](this._params),c!==!0);d--)if(c instanceof Promise)return this._preserveStack(3,p,d,a,h),c;d<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let x=this._escHandlers[this._collect<<8|s],_=x?x.length-1:-1;for(;_>=0&&(c=x[_](),c!==!0);_--)if(c instanceof Promise)return this._preserveStack(4,x,_,a,h),c;_<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function cf(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function nE(e,t=16){let[i,s,a]=e;return`rgb:${cf(i,t)}/${cf(s,t)}/${cf(a,t)}`}var rE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ns=131072,Fb=10;function qb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Wb=5e3,Gb=0,sE=class extends dt{constructor(e,t,i,s,a,o,c,h,p=new eE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new CC,this._utf8Decoder=new kC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone(),this._onRequestBell=this._register(new ke),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ke),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ke),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ke),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ke),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ke),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ke),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ke),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ke),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new _p(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(d=>this._activeBuffer=d.activeBuffer)),this._parser.setCsiHandlerFallback((d,x)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(d),params:x.toArray()})}),this._parser.setEscHandlerFallback(d=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(d)})}),this._parser.setExecuteHandlerFallback(d=>{this._logService.debug("Unknown EXECUTE code: ",{code:d})}),this._parser.setOscHandlerFallback((d,x,_)=>{this._logService.debug("Unknown OSC code: ",{identifier:d,action:x,data:_})}),this._parser.setDcsHandlerFallback((d,x,_)=>{x==="HOOK"&&(_=_.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(d),action:x,payload:_})}),this._parser.setPrintHandler((d,x,_)=>this.print(d,x,_)),this._parser.registerCsiHandler({final:"@"},d=>this.insertChars(d)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},d=>this.scrollLeft(d)),this._parser.registerCsiHandler({final:"A"},d=>this.cursorUp(d)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},d=>this.scrollRight(d)),this._parser.registerCsiHandler({final:"B"},d=>this.cursorDown(d)),this._parser.registerCsiHandler({final:"C"},d=>this.cursorForward(d)),this._parser.registerCsiHandler({final:"D"},d=>this.cursorBackward(d)),this._parser.registerCsiHandler({final:"E"},d=>this.cursorNextLine(d)),this._parser.registerCsiHandler({final:"F"},d=>this.cursorPrecedingLine(d)),this._parser.registerCsiHandler({final:"G"},d=>this.cursorCharAbsolute(d)),this._parser.registerCsiHandler({final:"H"},d=>this.cursorPosition(d)),this._parser.registerCsiHandler({final:"I"},d=>this.cursorForwardTab(d)),this._parser.registerCsiHandler({final:"J"},d=>this.eraseInDisplay(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},d=>this.eraseInDisplay(d,!0)),this._parser.registerCsiHandler({final:"K"},d=>this.eraseInLine(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},d=>this.eraseInLine(d,!0)),this._parser.registerCsiHandler({final:"L"},d=>this.insertLines(d)),this._parser.registerCsiHandler({final:"M"},d=>this.deleteLines(d)),this._parser.registerCsiHandler({final:"P"},d=>this.deleteChars(d)),this._parser.registerCsiHandler({final:"S"},d=>this.scrollUp(d)),this._parser.registerCsiHandler({final:"T"},d=>this.scrollDown(d)),this._parser.registerCsiHandler({final:"X"},d=>this.eraseChars(d)),this._parser.registerCsiHandler({final:"Z"},d=>this.cursorBackwardTab(d)),this._parser.registerCsiHandler({final:"`"},d=>this.charPosAbsolute(d)),this._parser.registerCsiHandler({final:"a"},d=>this.hPositionRelative(d)),this._parser.registerCsiHandler({final:"b"},d=>this.repeatPrecedingCharacter(d)),this._parser.registerCsiHandler({final:"c"},d=>this.sendDeviceAttributesPrimary(d)),this._parser.registerCsiHandler({prefix:">",final:"c"},d=>this.sendDeviceAttributesSecondary(d)),this._parser.registerCsiHandler({final:"d"},d=>this.linePosAbsolute(d)),this._parser.registerCsiHandler({final:"e"},d=>this.vPositionRelative(d)),this._parser.registerCsiHandler({final:"f"},d=>this.hVPosition(d)),this._parser.registerCsiHandler({final:"g"},d=>this.tabClear(d)),this._parser.registerCsiHandler({final:"h"},d=>this.setMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"h"},d=>this.setModePrivate(d)),this._parser.registerCsiHandler({final:"l"},d=>this.resetMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"l"},d=>this.resetModePrivate(d)),this._parser.registerCsiHandler({final:"m"},d=>this.charAttributes(d)),this._parser.registerCsiHandler({final:"n"},d=>this.deviceStatus(d)),this._parser.registerCsiHandler({prefix:"?",final:"n"},d=>this.deviceStatusPrivate(d)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},d=>this.softReset(d)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},d=>this.setCursorStyle(d)),this._parser.registerCsiHandler({final:"r"},d=>this.setScrollRegion(d)),this._parser.registerCsiHandler({final:"s"},d=>this.saveCursor(d)),this._parser.registerCsiHandler({final:"t"},d=>this.windowOptions(d)),this._parser.registerCsiHandler({final:"u"},d=>this.restoreCursor(d)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},d=>this.insertColumns(d)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},d=>this.deleteColumns(d)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},d=>this.selectProtected(d)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},d=>this.requestMode(d,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},d=>this.requestMode(d,!1)),this._parser.setExecuteHandler(pe.BEL,()=>this.bell()),this._parser.setExecuteHandler(pe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(pe.BS,()=>this.backspace()),this._parser.setExecuteHandler(pe.HT,()=>this.tab()),this._parser.setExecuteHandler(pe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(pe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(pu.IND,()=>this.index()),this._parser.setExecuteHandler(pu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(pu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Ln(d=>(this.setTitle(d),this.setIconName(d),!0))),this._parser.registerOscHandler(1,new Ln(d=>this.setIconName(d))),this._parser.registerOscHandler(2,new Ln(d=>this.setTitle(d))),this._parser.registerOscHandler(4,new Ln(d=>this.setOrReportIndexedColor(d))),this._parser.registerOscHandler(8,new Ln(d=>this.setHyperlink(d))),this._parser.registerOscHandler(10,new Ln(d=>this.setOrReportFgColor(d))),this._parser.registerOscHandler(11,new Ln(d=>this.setOrReportBgColor(d))),this._parser.registerOscHandler(12,new Ln(d=>this.setOrReportCursorColor(d))),this._parser.registerOscHandler(104,new Ln(d=>this.restoreIndexedColor(d))),this._parser.registerOscHandler(110,new Ln(d=>this.restoreFgColor(d))),this._parser.registerOscHandler(111,new Ln(d=>this.restoreBgColor(d))),this._parser.registerOscHandler(112,new Ln(d=>this.restoreCursorColor(d))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let d in Ai)this._parser.registerEscHandler({intermediates:"(",final:d},()=>this.selectCharset("("+d)),this._parser.registerEscHandler({intermediates:")",final:d},()=>this.selectCharset(")"+d)),this._parser.registerEscHandler({intermediates:"*",final:d},()=>this.selectCharset("*"+d)),this._parser.registerEscHandler({intermediates:"+",final:d},()=>this.selectCharset("+"+d)),this._parser.registerEscHandler({intermediates:"-",final:d},()=>this.selectCharset("-"+d)),this._parser.registerEscHandler({intermediates:".",final:d},()=>this.selectCharset("."+d)),this._parser.registerEscHandler({intermediates:"/",final:d},()=>this.selectCharset("/"+d));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(d=>(this._logService.error("Parsing error: ",d),d)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Ub((d,x)=>this.requestStatusString(d,x)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Wb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Wb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ns&&(o=this._parseStack.position+Ns)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,d=>String.fromCharCode(d)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(d=>d.charCodeAt(0)):e),this._parseBuffer.lengthNs)for(let d=o;d0&&_.getWidth(this._activeBuffer.x-1)===2&&_.setCellFromCodepoint(this._activeBuffer.x-1,0,1,x);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let N=_,L=this._activeBuffer.x-A;for(this._activeBuffer.x=A,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),A>0&&_ instanceof go&&_.copyCellsFrom(N,L,0,A,!1);L=0;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,x);continue}if(d&&(_.insertCells(this._activeBuffer.x,a-A,this._activeBuffer.getNullCell(x)),_.getWidth(h-1)===2&&_.setCellFromCodepoint(h-1,0,1,x)),_.setCellFromCodepoint(this._activeBuffer.x++,s,a,x),a>0)for(;--a;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,x)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&_.getWidth(this._activeBuffer.x)===0&&!_.hasContent(this._activeBuffer.x)&&_.setCellFromCodepoint(this._activeBuffer.x,0,1,x),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>qb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Ub(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Ln(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let d=1;d0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(pe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(pe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(pe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(pe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(pe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(E[E.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",E[E.SET=1]="SET",E[E.RESET=2]="RESET",E[E.PERMANENTLY_SET=3]="PERMANENTLY_SET",E[E.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:d,alt:x}=h,_=this._optionsService.rawOptions,b=(E,A)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${E};${A}$y`),!0),v=E=>E?1:2,y=e.params[0];return t?y===2?b(y,4):y===4?b(y,v(c.modes.insertMode)):y===12?b(y,3):y===20?b(y,v(_.convertEol)):b(y,0):y===1?b(y,v(s.applicationCursorKeys)):y===3?b(y,_.windowOptions.setWinLines?p===80?2:p===132?1:0:0):y===6?b(y,v(s.origin)):y===7?b(y,v(s.wraparound)):y===8?b(y,3):y===9?b(y,v(a==="X10")):y===12?b(y,v(_.cursorBlink)):y===25?b(y,v(!c.isCursorHidden)):y===45?b(y,v(s.reverseWraparound)):y===66?b(y,v(s.applicationKeypad)):y===67?b(y,4):y===1e3?b(y,v(a==="VT200")):y===1002?b(y,v(a==="DRAG")):y===1003?b(y,v(a==="ANY")):y===1004?b(y,v(s.sendFocus)):y===1005?b(y,4):y===1006?b(y,v(o==="SGR")):y===1015?b(y,4):y===1016?b(y,v(o==="SGR_PIXELS")):y===1048?b(y,1):y===47||y===1047||y===1049?b(y,v(d===x)):y===2004?b(y,v(s.bracketedPasteMode)):y===2026?b(y,v(s.synchronizedOutput)):b(y,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ao.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Si.fg,e.bg=Si.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Si.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Si.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Si.fg&16777215,s.bg&=-67108864,s.bg|=Si.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${pe.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Si.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!qb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Fb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Fb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Yb(o))if(a==="?")t.push({type:0,index:o});else{let c=$b(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=$b(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new ir;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},_p=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Gb=e,e=t,t=Gb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};_p=si([Me(0,hn)],_p);function Yb(e){return 0<=e&&e<256}var aE=5e7,Kb=12,lE=50,oE=class extends dt{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>aE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=Kb?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Kb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>lE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},xp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};xp=si([Me(0,hn)],xp);var Vb=!1,cE=class extends dt{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new al),this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onData=this._register(new ke),this.onData=this._onData.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ke),this._instantiationService=new D2,this.optionsService=this._register(new F2(e)),this._instantiationService.setService(dn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fp)),this._instantiationService.setService(hn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(dp)),this._instantiationService.setService(Ay,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pp)),this._instantiationService.setService(ca,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(jy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ra)),this._instantiationService.setService(jC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(K2),this._instantiationService.setService(TC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(xp),this._instantiationService.setService(Ry,this._oscLinkService),this._inputHandler=this._register(new sE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Yi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Yi.forward(this._bufferService.onResize,this._onResize)),this._register(Yi.forward(this.coreService.onData,this._onData)),this._register(Yi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new oE((t,i)=>this._inputHandler.parse(t,i))),this._register(Yi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ke),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Vb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Vb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,c0),t=Math.max(t,u0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Hb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Hb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Qt(()=>{for(let t of e)t.dispose()})}}},uE={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function hE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":pe.DEL,e.altKey&&(a.key=pe.ESC+a.key);break;case 9:if(e.shiftKey){a.key=pe.ESC+"[Z";break}a.key=pe.HT,a.cancel=!0;break;case 13:a.key=e.altKey?pe.ESC+pe.CR:pe.CR,a.cancel=!0;break;case 27:a.key=pe.ESC,e.altKey&&(a.key=pe.ESC+pe.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"D":t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"C":t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"A":t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"B":t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=pe.ESC+"[2~");break;case 46:o?a.key=pe.ESC+"[3;"+(o+1)+"~":a.key=pe.ESC+"[3~";break;case 36:o?a.key=pe.ESC+"[1;"+(o+1)+"H":t?a.key=pe.ESC+"OH":a.key=pe.ESC+"[H";break;case 35:o?a.key=pe.ESC+"[1;"+(o+1)+"F":t?a.key=pe.ESC+"OF":a.key=pe.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=pe.ESC+"[5;"+(o+1)+"~":a.key=pe.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=pe.ESC+"[6;"+(o+1)+"~":a.key=pe.ESC+"[6~";break;case 112:o?a.key=pe.ESC+"[1;"+(o+1)+"P":a.key=pe.ESC+"OP";break;case 113:o?a.key=pe.ESC+"[1;"+(o+1)+"Q":a.key=pe.ESC+"OQ";break;case 114:o?a.key=pe.ESC+"[1;"+(o+1)+"R":a.key=pe.ESC+"OR";break;case 115:o?a.key=pe.ESC+"[1;"+(o+1)+"S":a.key=pe.ESC+"OS";break;case 116:o?a.key=pe.ESC+"[15;"+(o+1)+"~":a.key=pe.ESC+"[15~";break;case 117:o?a.key=pe.ESC+"[17;"+(o+1)+"~":a.key=pe.ESC+"[17~";break;case 118:o?a.key=pe.ESC+"[18;"+(o+1)+"~":a.key=pe.ESC+"[18~";break;case 119:o?a.key=pe.ESC+"[19;"+(o+1)+"~":a.key=pe.ESC+"[19~";break;case 120:o?a.key=pe.ESC+"[20;"+(o+1)+"~":a.key=pe.ESC+"[20~";break;case 121:o?a.key=pe.ESC+"[21;"+(o+1)+"~":a.key=pe.ESC+"[21~";break;case 122:o?a.key=pe.ESC+"[23;"+(o+1)+"~":a.key=pe.ESC+"[23~";break;case 123:o?a.key=pe.ESC+"[24;"+(o+1)+"~":a.key=pe.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=pe.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=pe.DEL:e.keyCode===219?a.key=pe.ESC:e.keyCode===220?a.key=pe.FS:e.keyCode===221&&(a.key=pe.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=uE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=pe.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,d=String.fromCharCode(p);e.shiftKey&&(d=d.toUpperCase()),a.key=pe.ESC+d}else if(e.keyCode===32)a.key=pe.ESC+(e.ctrlKey?pe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=pe.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=pe.US),e.key==="@"&&(a.key=pe.NUL));break}return a}var ui=0,dE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Nu,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Nu,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(ui=this._search(t),ui===-1)||this._getKey(this._array[ui])!==t)return!1;do if(this._array[ui]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(ui),!0;while(++uia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ui=this._search(e),!(ui<0||ui>=this._array.length)&&this._getKey(this._array[ui])===e))do yield this._array[ui];while(++ui=this._array.length)&&this._getKey(this._array[ui])===e))do t(this._array[ui]);while(++ui=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},uf=0,Xb=0,fE=class extends dt{constructor(){super(),this._decorations=new dE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ke),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ke),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Qt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new pE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{uf=a.options.x??0,Xb=uf+(a.options.width??1),e>=uf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Zb=20,Tu=class extends dt{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new gE(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ye(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Qt(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Zb+1&&(this._liveRegion.textContent+=Pf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),d=this._rowElements[a];d&&(h.length===0?(d.textContent=" ",this._rowColumns.set(d,[0,1])):(d.textContent=h,this._rowColumns.set(d,c)),d.setAttribute("aria-posinset",p),d.setAttribute("aria-setsize",s),this._alignRowWidth(d))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:d})=>{let x=p instanceof Text?p.parentNode:p,_=parseInt(x==null?void 0:x.getAttribute("aria-posinset"),10)-1;if(isNaN(_))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(x);if(!b)return console.warn("columns is null. Race condition?"),null;let v=d=this._terminal.cols&&(++_,v=0),{row:_,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ye(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ye(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ye(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ye(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var d,x;if(this._isMouseOut)return;let p=h==null?void 0:h.map(_=>({link:_}));(d=this._activeProviderReplies)==null||d.set(o,p),i=this._checkLinkProviderResult(o,e,i),((x=this._activeProviderReplies)==null?void 0:x.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let d=h;d<=p;d++){if(i.has(d)){a.splice(o--,1);break}i.add(d)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&_E(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};bp=si([Me(1,Ip),Me(2,Jr),Me(3,hn),Me(4,Dy)],bp);function _E(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var xE=class extends cE{constructor(e={}){super(e),this._linkifier=this._register(new al),this.browser=Qy,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new al),this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ke),this.onKey=this._onKey.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ke),this.onBell=this._onBell.event,this._onFocus=this._register(new ke),this._onBlur=this._register(new ke),this._onA11yCharEmitter=this._register(new ke),this._onA11yTabEmitter=this._register(new ke),this._onWillOpen=this._register(new ke),this._setup(),this._decorationService=this._instantiationService.createInstance(fE),this._instantiationService.setService(Ro,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(l2),this._instantiationService.setService(Dy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Hf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Yi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Yi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Yi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Yi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Qt(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Vt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${nE(a)}${Xy.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=wi.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=wi.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ye(this.element,"copy",t=>{this.hasSelection()&&SC(t,this._selectionService)}));let e=t=>wC(t,this.textarea,this.coreService,this.optionsService);this._register(Ye(this.textarea,"paste",e)),this._register(Ye(this.element,"paste",e)),Jy?this._register(Ye(this.element,"mousedown",t=>{t.button===2&&lb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ye(this.element,"contextmenu",t=>{lb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Yp&&this._register(Ye(this.element,"auxclick",t=>{t.button===1&&Cy(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ye(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ye(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ye(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ye(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ye(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ye(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ye(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ye(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",zf.get()),i0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(s2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Qr,this._coreBrowserService),this._register(Ye(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ye(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(lp,this._document,this._helperContainer),this._instantiationService.setService(Lu,this._charSizeService),this._themeService=this._instantiationService.createInstance(hp),this._instantiationService.setService(cl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ku),this._instantiationService.setService(My,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cp,this.rows,this.screenElement)),this._instantiationService.setService(Jr,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(rp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(op),this._instantiationService.setService(Ip,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(bp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ip,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(up,this.element,this.screenElement,s)),this._instantiationService.setService(RC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(Yi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(np,this.screenElement)),this._register(Ye(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ap,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var d,x,_,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let y=o.deltaY;if(y===0||e.coreMouseService.consumeWheelEvent(o,(b=(_=(x=(d=e._renderService)==null?void 0:d.dimensions)==null?void 0:x.device)==null?void 0:_.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=y<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ye(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ye(t,"wheel",o=>{var c,h,p,d,x;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(d=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:d.height,(x=e._coreBrowserService)==null?void 0:x.dpr)===0)return this.cancel(o,!0);let _=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(_,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){wy(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=hE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===pe.ETX||i.key===pe.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(bE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new ir)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Qb=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new yE(t)}getNullCell(){return new ir}},SE=class extends dt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new Qb(this._core.buffers.normal,"normal"),this._alternate=new Qb(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},wE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},CE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},kE=["cols","rows"],vr=0,EE=class extends dt{constructor(e){super(),this._core=this._register(new xE(e)),this._addonManager=this._register(new vE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(kE.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new wE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new CE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new SE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return zf.get()},set promptLabel(e){zf.set(e)},get tooMuchOutput(){return Pf.get()},set tooMuchOutput(e){Pf.set(e)}}}_verifyIntegers(...e){for(vr of e)if(vr===1/0||isNaN(vr)||vr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(vr of e)if(vr&&(vr===1/0||isNaN(vr)||vr%1!==0||vr<0))throw new Error("This API only accepts positive integers")}};/** +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Yp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=jb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Gp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-rf),rf),t/=rf,t/Math.abs(t)+Math.round(t*(T2-1)))}shouldForceSelection(e){return Eu?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),j2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Eu&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,d=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=D-1,p+=D-1);A>0&&h>0&&!this._isCharWordSeparator(o.loadCell(A-1,this._workCell));){o.loadCell(A-1,this._workCell);let P=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,A--):P>1&&(b+=P-1,h-=P-1),h--,A--}for(;E1&&(v+=P-1,p+=P-1),p++,E++}}p++;let y=h+d-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&y===0&&o.getCodePoint(0)!==32){let A=a.lines.get(e[1]-1);if(A&&o.isWrapped&&A.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let D=this._bufferService.cols-E.start;y-=D,N+=D}}}if(s&&y+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let A=a.lines.get(e[1]+1);if(A!=null&&A.isWrapped&&A.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:y,length:N}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=jb(i,this._bufferService.cols)}};up=oi([Me(3,fn),Me(4,ca),Me(5,Ip),Me(6,pn),Me(7,Jr),Me(8,Qr)],up);var Ab=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Rb=class{constructor(){this._color=new Ab,this._css=new Ab}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[ni.toColor("#2e3436"),ni.toColor("#cc0000"),ni.toColor("#4e9a06"),ni.toColor("#c4a000"),ni.toColor("#3465a4"),ni.toColor("#75507b"),ni.toColor("#06989a"),ni.toColor("#d3d7cf"),ni.toColor("#555753"),ni.toColor("#ef2929"),ni.toColor("#8ae234"),ni.toColor("#fce94f"),ni.toColor("#729fcf"),ni.toColor("#ad7fa8"),ni.toColor("#34e2e2"),ni.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Ci.toCss(s,a,o),rgba:Ci.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ci.toCss(s,s,s),rgba:Ci.toRgba(s,s,s)})}return e})()),ia=ni.toColor("#ffffff"),mo=ni.toColor("#000000"),Mb=ni.toColor("#ffffff"),Db=mo,so={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},D2=ia,hp=class extends ft{constructor(e){super(),this._optionsService=e,this._contrastCache=new Rb,this._halfContrastCache=new Rb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ia,background:mo,cursor:Mb,cursorAccent:Db,selectionForeground:void 0,selectionBackgroundTransparent:so,selectionBackgroundOpaque:Xt.blend(mo,so),selectionInactiveBackgroundTransparent:so,selectionInactiveBackgroundOpaque:Xt.blend(mo,so),scrollbarSliderBackground:Xt.opacity(ia,.2),scrollbarSliderHoverBackground:Xt.opacity(ia,.4),scrollbarSliderActiveBackground:Xt.opacity(ia,.5),overviewRulerBorder:ia,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Ut(e.foreground,ia),t.background=Ut(e.background,mo),t.cursor=Xt.blend(t.background,Ut(e.cursor,Mb)),t.cursorAccent=Xt.blend(t.background,Ut(e.cursorAccent,Db)),t.selectionBackgroundTransparent=Ut(e.selectionBackground,so),t.selectionBackgroundOpaque=Xt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Ut(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Xt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Ut(e.selectionForeground,Eb):void 0,t.selectionForeground===Eb&&(t.selectionForeground=void 0),Xt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Xt.opacity(t.selectionBackgroundTransparent,.3)),Xt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Xt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Ut(e.scrollbarSliderBackground,Xt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Ut(e.scrollbarSliderHoverBackground,Xt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Ut(e.scrollbarSliderActiveBackground,Xt.opacity(t.foreground,.5)),t.overviewRulerBorder=Ut(e.overviewRulerBorder,D2),t.ansi=Ti.slice(),t.ansi[0]=Ut(e.black,Ti[0]),t.ansi[1]=Ut(e.red,Ti[1]),t.ansi[2]=Ut(e.green,Ti[2]),t.ansi[3]=Ut(e.yellow,Ti[3]),t.ansi[4]=Ut(e.blue,Ti[4]),t.ansi[5]=Ut(e.magenta,Ti[5]),t.ansi[6]=Ut(e.cyan,Ti[6]),t.ansi[7]=Ut(e.white,Ti[7]),t.ansi[8]=Ut(e.brightBlack,Ti[8]),t.ansi[9]=Ut(e.brightRed,Ti[9]),t.ansi[10]=Ut(e.brightGreen,Ti[10]),t.ansi[11]=Ut(e.brightYellow,Ti[11]),t.ansi[12]=Ut(e.brightBlue,Ti[12]),t.ansi[13]=Ut(e.brightMagenta,Ti[13]),t.ansi[14]=Ut(e.brightCyan,Ti[14]),t.ansi[15]=Ut(e.brightWhite,Ti[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},O2={trace:0,debug:1,info:2,warn:3,error:4,off:5},z2="xterm.js: ",dp=class extends ft{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=O2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*dt+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*dt+0]=t|2097152|i[2]<<22):this._data[t*dt+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*dt+0]>>22}hasWidth(t){return this._data[t*dt+0]&12582912}getFg(t){return this._data[t*dt+1]}getBg(t){return this._data[t*dt+2]}hasContent(t){return this._data[t*dt+0]&4194303}getCodePoint(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*dt+0]&2097152}getString(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t]:i&2097151?js(i&2097151):""}isProtected(t){return this._data[t*dt+2]&536870912}loadCell(t,i){return Jc=t*dt,i.content=this._data[Jc+0],i.fg=this._data[Jc+1],i.bg=this._data[Jc+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*dt+0]=i.content,this._data[t*dt+1]=i.fg,this._data[t*dt+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*dt+0]=i|s<<22,this._data[t*dt+1]=a.fg,this._data[t*dt+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*dt+0];a&2097152?this._combined[t]+=js(i):a&2097151?(this._combined[t]=js(a&2097151)+js(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*dt+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*sf=0;--t)if(this._data[t*dt+0]&4194303)return t+(this._data[t*dt+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*dt+0]&4194303||this._data[t*dt+2]&50331648)return t+(this._data[t*dt+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let d=0;d=i&&(this._combined[d-i+s]=t._combined[d])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function P2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(A>x||_[A].getTrimmedLength()===0);A--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function I2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cko(e,d,t)).reduce((p,d)=>p+d),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let d=e[c].getWidth(o-1)===2;d&&o--;let _=d?i-1:i;s.push(_),h+=_}return s}function ko(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var o0=class c0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=c0._nextId++,this._onDispose=this.register(new ke),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),aa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};o0._nextId=1;var $2=o0,Ri={},na=Ri.B;Ri[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Ri.A={"#":"£"};Ri.B=void 0;Ri[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Ri.C=Ri[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Ri.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Ri.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Ri.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Ri.E=Ri[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Ri.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Ri.H=Ri[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Lb=4294967295,Ob=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=wi.clone(),this.savedCharset=na,this.markers=[],this._nullCell=sr.fromCharData([0,Ey,1,0]),this._whitespaceCell=sr.fromCharData([0,Rs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Nu,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new wu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new wu),this._whitespaceCell}getBlankLine(e,t){return new go(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eLb?Lb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=wi);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(wi),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new go(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=P2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(wi),i);if(s.length>0){let a=I2(this.lines,s);H2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(wi),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let P=this.ybase+this.y;if(P>=c&&P0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let y=_.length-1,N=_[y];N===0&&(y--,N=_[y]);let A=p.length-x-1,E=d;for(;A>=0;){let P=Math.min(E,N);if(p[y]===void 0)break;if(p[y].copyCellsFrom(p[A],E-P,N-P,P,!0),N-=P,N===0&&(y--,N=_[y]),E-=P,E===0){A--;let J=Math.max(A,0);E=ko(p,J,this._cols)}}for(let P=0;P0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>d+b){for(let A=x.newLines.length-1;A>=0;A--)this.lines.set(N--,x.newLines[A]);N++,c.push({index:d+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[d--]);let v=0;for(let N=c.length-1;N>=0;N--)c[N].index+=v,this.lines.onInsertEmitter.fire(c[N]),v+=c[N].amount;let y=Math.max(0,p+o-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},F2=class extends ft{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ke),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ob(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ob(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},u0=2,h0=1,fp=class extends ft{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,u0),this.rows=Math.max(e.rawOptions.rows||0,h0),this.buffers=this._register(new F2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};fp=oi([Me(0,pn)],fp);var Va={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Eu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},q2=["normal","bold","100","200","300","400","500","600","700","800","900"],W2=class extends ft{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...Va};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Jt(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Va[e]),!G2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Va[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=q2.includes(t)?t:Va[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function G2(e){return e==="block"||e==="underline"||e==="bar"}function xo(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&xo(e[s],t-1);return i}var zb=Object.freeze({insertMode:!1}),Pb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ke),this.onData=this._onData.event,this._onUserInput=this._register(new ke),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ke),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=xo(zb),this.decPrivateModes=xo(Pb)}reset(){this.modes=xo(zb),this.decPrivateModes=xo(Pb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pp=oi([Me(0,fn),Me(1,Ry),Me(2,pn)],pp);var Ib={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function af(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var lf=String.fromCharCode,Hb={DEFAULT:e=>{let t=[af(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${lf(t[0])}${lf(t[1])}${lf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.x};${e.y}${t}`}},mp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ke),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Ib))this.addProtocol(s,Ib[s]);for(let s of Object.keys(Hb))this.addEncoding(s,Hb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mp=oi([Me(0,fn),Me(1,ca),Me(2,pn)],mp);var of=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Y2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],ji;function K2(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ra.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ra.createPropertyValue(0,i,s)}},ra=class gu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new V2;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let d=t.charCodeAt(o);56320<=d&&d<=57343?c=(c-55296)*1024+d-56320+65536:i+=this.wcwidth(d)}let h=this.charProperties(c,s),p=gu.extractWidth(h);gu.extractShouldJoin(h)&&(p-=gu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},X2=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ub(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ao=2147483647,Z2=256,d0=class gp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>Z2)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new gp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ao?ao:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>ao?ao:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,ao):t}},lo=[],Q2=class{constructor(){this._state=0,this._active=lo,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=lo}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=lo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lo,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=lo,this._id=-1,this._state=0}}},Hn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},oo=[],J2=class{constructor(){this._handlers=Object.create(null),this._active=oo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=oo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=oo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||oo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=oo,this._ident=0}},_o=new d0;_o.addParam(0);var $b=class{constructor(e){this._handler=e,this._data="",this._params=_o,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_o,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=_o,this._data="",this._hitLimit=!1,i));return this._params=_o,this._data="",this._hitLimit=!1,t}},eE=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(nr,0,2,0),e.add(nr,8,5,8),e.add(nr,6,0,6),e.add(nr,11,0,11),e.add(nr,13,13,13),e})(),iE=class extends ft{constructor(e=tE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new d0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Jt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Q2),this._dcsParser=this._register(new J2),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[d](this._params),c!==!0);d--)if(c instanceof Promise)return this._preserveStack(3,p,d,a,h),c;d<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function cf(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function sE(e,t=16){let[i,s,a]=e;return`rgb:${cf(i,t)}/${cf(s,t)}/${cf(a,t)}`}var aE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ns=131072,qb=10;function Wb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Gb=5e3,Yb=0,lE=class extends ft{constructor(e,t,i,s,a,o,c,h,p=new iE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new EC,this._utf8Decoder=new NC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone(),this._onRequestBell=this._register(new ke),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ke),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ke),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ke),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ke),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ke),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ke),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ke),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ke),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new xp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(d=>this._activeBuffer=d.activeBuffer)),this._parser.setCsiHandlerFallback((d,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(d),params:_.toArray()})}),this._parser.setEscHandlerFallback(d=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(d)})}),this._parser.setExecuteHandlerFallback(d=>{this._logService.debug("Unknown EXECUTE code: ",{code:d})}),this._parser.setOscHandlerFallback((d,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:d,action:_,data:x})}),this._parser.setDcsHandlerFallback((d,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(d),action:_,payload:x})}),this._parser.setPrintHandler((d,_,x)=>this.print(d,_,x)),this._parser.registerCsiHandler({final:"@"},d=>this.insertChars(d)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},d=>this.scrollLeft(d)),this._parser.registerCsiHandler({final:"A"},d=>this.cursorUp(d)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},d=>this.scrollRight(d)),this._parser.registerCsiHandler({final:"B"},d=>this.cursorDown(d)),this._parser.registerCsiHandler({final:"C"},d=>this.cursorForward(d)),this._parser.registerCsiHandler({final:"D"},d=>this.cursorBackward(d)),this._parser.registerCsiHandler({final:"E"},d=>this.cursorNextLine(d)),this._parser.registerCsiHandler({final:"F"},d=>this.cursorPrecedingLine(d)),this._parser.registerCsiHandler({final:"G"},d=>this.cursorCharAbsolute(d)),this._parser.registerCsiHandler({final:"H"},d=>this.cursorPosition(d)),this._parser.registerCsiHandler({final:"I"},d=>this.cursorForwardTab(d)),this._parser.registerCsiHandler({final:"J"},d=>this.eraseInDisplay(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},d=>this.eraseInDisplay(d,!0)),this._parser.registerCsiHandler({final:"K"},d=>this.eraseInLine(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},d=>this.eraseInLine(d,!0)),this._parser.registerCsiHandler({final:"L"},d=>this.insertLines(d)),this._parser.registerCsiHandler({final:"M"},d=>this.deleteLines(d)),this._parser.registerCsiHandler({final:"P"},d=>this.deleteChars(d)),this._parser.registerCsiHandler({final:"S"},d=>this.scrollUp(d)),this._parser.registerCsiHandler({final:"T"},d=>this.scrollDown(d)),this._parser.registerCsiHandler({final:"X"},d=>this.eraseChars(d)),this._parser.registerCsiHandler({final:"Z"},d=>this.cursorBackwardTab(d)),this._parser.registerCsiHandler({final:"`"},d=>this.charPosAbsolute(d)),this._parser.registerCsiHandler({final:"a"},d=>this.hPositionRelative(d)),this._parser.registerCsiHandler({final:"b"},d=>this.repeatPrecedingCharacter(d)),this._parser.registerCsiHandler({final:"c"},d=>this.sendDeviceAttributesPrimary(d)),this._parser.registerCsiHandler({prefix:">",final:"c"},d=>this.sendDeviceAttributesSecondary(d)),this._parser.registerCsiHandler({final:"d"},d=>this.linePosAbsolute(d)),this._parser.registerCsiHandler({final:"e"},d=>this.vPositionRelative(d)),this._parser.registerCsiHandler({final:"f"},d=>this.hVPosition(d)),this._parser.registerCsiHandler({final:"g"},d=>this.tabClear(d)),this._parser.registerCsiHandler({final:"h"},d=>this.setMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"h"},d=>this.setModePrivate(d)),this._parser.registerCsiHandler({final:"l"},d=>this.resetMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"l"},d=>this.resetModePrivate(d)),this._parser.registerCsiHandler({final:"m"},d=>this.charAttributes(d)),this._parser.registerCsiHandler({final:"n"},d=>this.deviceStatus(d)),this._parser.registerCsiHandler({prefix:"?",final:"n"},d=>this.deviceStatusPrivate(d)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},d=>this.softReset(d)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},d=>this.setCursorStyle(d)),this._parser.registerCsiHandler({final:"r"},d=>this.setScrollRegion(d)),this._parser.registerCsiHandler({final:"s"},d=>this.saveCursor(d)),this._parser.registerCsiHandler({final:"t"},d=>this.windowOptions(d)),this._parser.registerCsiHandler({final:"u"},d=>this.restoreCursor(d)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},d=>this.insertColumns(d)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},d=>this.deleteColumns(d)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},d=>this.selectProtected(d)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},d=>this.requestMode(d,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},d=>this.requestMode(d,!1)),this._parser.setExecuteHandler(pe.BEL,()=>this.bell()),this._parser.setExecuteHandler(pe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(pe.BS,()=>this.backspace()),this._parser.setExecuteHandler(pe.HT,()=>this.tab()),this._parser.setExecuteHandler(pe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(pe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(pu.IND,()=>this.index()),this._parser.setExecuteHandler(pu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(pu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Hn(d=>(this.setTitle(d),this.setIconName(d),!0))),this._parser.registerOscHandler(1,new Hn(d=>this.setIconName(d))),this._parser.registerOscHandler(2,new Hn(d=>this.setTitle(d))),this._parser.registerOscHandler(4,new Hn(d=>this.setOrReportIndexedColor(d))),this._parser.registerOscHandler(8,new Hn(d=>this.setHyperlink(d))),this._parser.registerOscHandler(10,new Hn(d=>this.setOrReportFgColor(d))),this._parser.registerOscHandler(11,new Hn(d=>this.setOrReportBgColor(d))),this._parser.registerOscHandler(12,new Hn(d=>this.setOrReportCursorColor(d))),this._parser.registerOscHandler(104,new Hn(d=>this.restoreIndexedColor(d))),this._parser.registerOscHandler(110,new Hn(d=>this.restoreFgColor(d))),this._parser.registerOscHandler(111,new Hn(d=>this.restoreBgColor(d))),this._parser.registerOscHandler(112,new Hn(d=>this.restoreCursorColor(d))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let d in Ri)this._parser.registerEscHandler({intermediates:"(",final:d},()=>this.selectCharset("("+d)),this._parser.registerEscHandler({intermediates:")",final:d},()=>this.selectCharset(")"+d)),this._parser.registerEscHandler({intermediates:"*",final:d},()=>this.selectCharset("*"+d)),this._parser.registerEscHandler({intermediates:"+",final:d},()=>this.selectCharset("+"+d)),this._parser.registerEscHandler({intermediates:"-",final:d},()=>this.selectCharset("-"+d)),this._parser.registerEscHandler({intermediates:".",final:d},()=>this.selectCharset("."+d)),this._parser.registerEscHandler({intermediates:"/",final:d},()=>this.selectCharset("/"+d));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(d=>(this._logService.error("Parsing error: ",d),d)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new $b((d,_)=>this.requestStatusString(d,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Gb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Gb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ns&&(o=this._parseStack.position+Ns)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,d=>String.fromCharCode(d)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(d=>d.charCodeAt(0)):e),this._parseBuffer.lengthNs)for(let d=o;d0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,D=this._activeBuffer.x-A;for(this._activeBuffer.x=A,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),A>0&&x instanceof go&&x.copyCellsFrom(E,D,0,A,!1);D=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(d&&(x.insertCells(this._activeBuffer.x,a-A,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Wb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new $b(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Hn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let d=1;d0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(pe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(pe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(pe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(pe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(pe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(N[N.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",N[N.SET=1]="SET",N[N.RESET=2]="RESET",N[N.PERMANENTLY_SET=3]="PERMANENTLY_SET",N[N.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:d,alt:_}=h,x=this._optionsService.rawOptions,b=(N,A)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${A}$y`),!0),v=N=>N?1:2,y=e.params[0];return t?y===2?b(y,4):y===4?b(y,v(c.modes.insertMode)):y===12?b(y,3):y===20?b(y,v(x.convertEol)):b(y,0):y===1?b(y,v(s.applicationCursorKeys)):y===3?b(y,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):y===6?b(y,v(s.origin)):y===7?b(y,v(s.wraparound)):y===8?b(y,3):y===9?b(y,v(a==="X10")):y===12?b(y,v(x.cursorBlink)):y===25?b(y,v(!c.isCursorHidden)):y===45?b(y,v(s.reverseWraparound)):y===66?b(y,v(s.applicationKeypad)):y===67?b(y,4):y===1e3?b(y,v(a==="VT200")):y===1002?b(y,v(a==="DRAG")):y===1003?b(y,v(a==="ANY")):y===1004?b(y,v(s.sendFocus)):y===1005?b(y,4):y===1006?b(y,v(o==="SGR")):y===1015?b(y,4):y===1016?b(y,v(o==="SGR_PIXELS")):y===1048?b(y,1):y===47||y===1047||y===1049?b(y,v(d===_)):y===2004?b(y,v(s.bracketedPasteMode)):y===2026?b(y,v(s.synchronizedOutput)):b(y,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ao.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=wi.fg,e.bg=wi.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=wi.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=wi.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=wi.fg&16777215,s.bg&=-67108864,s.bg|=wi.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${pe.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=wi.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Wb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>qb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>qb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Kb(o))if(a==="?")t.push({type:0,index:o});else{let c=Fb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Fb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},xp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Yb=e,e=t,t=Yb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};xp=oi([Me(0,fn)],xp);function Kb(e){return 0<=e&&e<256}var oE=5e7,Vb=12,cE=50,uE=class extends ft{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>oE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=Vb?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Vb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>cE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},_p=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};_p=oi([Me(0,fn)],_p);var Xb=!1,hE=class extends ft{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new sl),this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onData=this._register(new ke),this.onData=this._onData.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ke),this._instantiationService=new L2,this.optionsService=this._register(new W2(e)),this._instantiationService.setService(pn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fp)),this._instantiationService.setService(fn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(dp)),this._instantiationService.setService(Ry,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pp)),this._instantiationService.setService(ca,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(Ay,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ra)),this._instantiationService.setService(RC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(X2),this._instantiationService.setService(AC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_p),this._instantiationService.setService(My,this._oscLinkService),this._inputHandler=this._register(new lE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Vi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Vi.forward(this._bufferService.onResize,this._onResize)),this._register(Vi.forward(this.coreService.onData,this._onData)),this._register(Vi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new uE((t,i)=>this._inputHandler.parse(t,i))),this._register(Vi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ke),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Xb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Xb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,u0),t=Math.max(t,h0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ub.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ub(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Jt(()=>{for(let t of e)t.dispose()})}}},dE={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function fE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":pe.DEL,e.altKey&&(a.key=pe.ESC+a.key);break;case 9:if(e.shiftKey){a.key=pe.ESC+"[Z";break}a.key=pe.HT,a.cancel=!0;break;case 13:a.key=e.altKey?pe.ESC+pe.CR:pe.CR,a.cancel=!0;break;case 27:a.key=pe.ESC,e.altKey&&(a.key=pe.ESC+pe.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"D":t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"C":t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"A":t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"B":t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=pe.ESC+"[2~");break;case 46:o?a.key=pe.ESC+"[3;"+(o+1)+"~":a.key=pe.ESC+"[3~";break;case 36:o?a.key=pe.ESC+"[1;"+(o+1)+"H":t?a.key=pe.ESC+"OH":a.key=pe.ESC+"[H";break;case 35:o?a.key=pe.ESC+"[1;"+(o+1)+"F":t?a.key=pe.ESC+"OF":a.key=pe.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=pe.ESC+"[5;"+(o+1)+"~":a.key=pe.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=pe.ESC+"[6;"+(o+1)+"~":a.key=pe.ESC+"[6~";break;case 112:o?a.key=pe.ESC+"[1;"+(o+1)+"P":a.key=pe.ESC+"OP";break;case 113:o?a.key=pe.ESC+"[1;"+(o+1)+"Q":a.key=pe.ESC+"OQ";break;case 114:o?a.key=pe.ESC+"[1;"+(o+1)+"R":a.key=pe.ESC+"OR";break;case 115:o?a.key=pe.ESC+"[1;"+(o+1)+"S":a.key=pe.ESC+"OS";break;case 116:o?a.key=pe.ESC+"[15;"+(o+1)+"~":a.key=pe.ESC+"[15~";break;case 117:o?a.key=pe.ESC+"[17;"+(o+1)+"~":a.key=pe.ESC+"[17~";break;case 118:o?a.key=pe.ESC+"[18;"+(o+1)+"~":a.key=pe.ESC+"[18~";break;case 119:o?a.key=pe.ESC+"[19;"+(o+1)+"~":a.key=pe.ESC+"[19~";break;case 120:o?a.key=pe.ESC+"[20;"+(o+1)+"~":a.key=pe.ESC+"[20~";break;case 121:o?a.key=pe.ESC+"[21;"+(o+1)+"~":a.key=pe.ESC+"[21~";break;case 122:o?a.key=pe.ESC+"[23;"+(o+1)+"~":a.key=pe.ESC+"[23~";break;case 123:o?a.key=pe.ESC+"[24;"+(o+1)+"~":a.key=pe.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=pe.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=pe.DEL:e.keyCode===219?a.key=pe.ESC:e.keyCode===220?a.key=pe.FS:e.keyCode===221&&(a.key=pe.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=dE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=pe.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,d=String.fromCharCode(p);e.shiftKey&&(d=d.toUpperCase()),a.key=pe.ESC+d}else if(e.keyCode===32)a.key=pe.ESC+(e.ctrlKey?pe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=pe.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=pe.US),e.key==="@"&&(a.key=pe.NUL));break}return a}var di=0,pE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Nu,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Nu,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(di=this._search(t),di===-1)||this._getKey(this._array[di])!==t)return!1;do if(this._array[di]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(di),!0;while(++dia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(di=this._search(e),!(di<0||di>=this._array.length)&&this._getKey(this._array[di])===e))do yield this._array[di];while(++di=this._array.length)&&this._getKey(this._array[di])===e))do t(this._array[di]);while(++di=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},uf=0,Zb=0,mE=class extends ft{constructor(){super(),this._decorations=new pE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ke),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ke),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Jt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new gE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{uf=a.options.x??0,Zb=uf+(a.options.width??1),e>=uf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Qb=20,Tu=class extends ft{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new _E(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ye(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Jt(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Qb+1&&(this._liveRegion.textContent+=Pf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),d=this._rowElements[a];d&&(h.length===0?(d.textContent=" ",this._rowColumns.set(d,[0,1])):(d.textContent=h,this._rowColumns.set(d,c)),d.setAttribute("aria-posinset",p),d.setAttribute("aria-setsize",s),this._alignRowWidth(d))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:d})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=d=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ye(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ye(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ye(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ye(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var d,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(d=this._activeProviderReplies)==null||d.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let d=h;d<=p;d++){if(i.has(d)){a.splice(o--,1);break}i.add(d)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&bE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};bp=oi([Me(1,Ip),Me(2,Jr),Me(3,fn),Me(4,By)],bp);function bE(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var vE=class extends hE{constructor(e={}){super(e),this._linkifier=this._register(new sl),this.browser=Jy,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new sl),this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ke),this.onKey=this._onKey.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ke),this.onBell=this._onBell.event,this._onFocus=this._register(new ke),this._onBlur=this._register(new ke),this._onA11yCharEmitter=this._register(new ke),this._onA11yTabEmitter=this._register(new ke),this._onWillOpen=this._register(new ke),this._setup(),this._decorationService=this._instantiationService.createInstance(mE),this._instantiationService.setService(Ro,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(c2),this._instantiationService.setService(By,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Hf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Vi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Vi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Vi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Vi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Jt(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Xt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${sE(a)}${Zy.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ci.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ci.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ye(this.element,"copy",t=>{this.hasSelection()&&CC(t,this._selectionService)}));let e=t=>kC(t,this.textarea,this.coreService,this.optionsService);this._register(Ye(this.textarea,"paste",e)),this._register(Ye(this.element,"paste",e)),e0?this._register(Ye(this.element,"mousedown",t=>{t.button===2&&ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ye(this.element,"contextmenu",t=>{ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Yp&&this._register(Ye(this.element,"auxclick",t=>{t.button===1&&ky(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ye(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ye(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ye(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ye(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ye(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ye(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ye(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ye(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",zf.get()),n0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(l2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Qr,this._coreBrowserService),this._register(Ye(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ye(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(lp,this._document,this._helperContainer),this._instantiationService.setService(Lu,this._charSizeService),this._themeService=this._instantiationService.createInstance(hp),this._instantiationService.setService(ol,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ku),this._instantiationService.setService(Dy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cp,this.rows,this.screenElement)),this._instantiationService.setService(Jr,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(rp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(op),this._instantiationService.setService(Ip,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(bp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ip,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(up,this.element,this.screenElement,s)),this._instantiationService.setService(DC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(Vi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(np,this.screenElement)),this._register(Ye(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ap,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var d,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let y=o.deltaY;if(y===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(d=e._renderService)==null?void 0:d.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=y<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ye(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ye(t,"wheel",o=>{var c,h,p,d,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(d=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:d.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Cy(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=fE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===pe.ETX||i.key===pe.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(yE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new sr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Jb=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new wE(t)}getNullCell(){return new sr}},CE=class extends ft{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new Jb(this._core.buffers.normal,"normal"),this._alternate=new Jb(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},kE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},EE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},NE=["cols","rows"],yr=0,TE=class extends ft{constructor(e){super(),this._core=this._register(new vE(e)),this._addonManager=this._register(new SE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(NE.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new kE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new EE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new CE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return zf.get()},set promptLabel(e){zf.set(e)},get tooMuchOutput(){return Pf.get()},set tooMuchOutput(e){Pf.set(e)}}}_verifyIntegers(...e){for(yr of e)if(yr===1/0||isNaN(yr)||yr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(yr of e)if(yr&&(yr===1/0||isNaN(yr)||yr%1!==0||yr<0))throw new Error("This API only accepts positive integers")}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -83,7 +83,7 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var NE=2,TE=1,jE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var _;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((_=this._terminal.options.overviewRuler)==null?void 0:_.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,d=s-h,x=a-p-t;return{cols:Math.max(NE,Math.floor(x/e.css.cell.width)),rows:Math.max(TE,Math.floor(d/e.css.cell.height))}}};/** + */var jE=2,AE=1,RE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var x;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((x=this._terminal.options.overviewRuler)==null?void 0:x.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,d=s-h,_=a-p-t;return{cols:Math.max(jE,Math.floor(_/e.css.cell.width)),rows:Math.max(AE,Math.floor(d/e.css.cell.height))}}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -94,50 +94,50 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var Oi=0,zi=0,Pi=0,ri=0,Qi;(e=>{function t(a,o,c,h){return h!==void 0?`#${Js(a)}${Js(o)}${Js(c)}${Js(h)}`:`#${Js(a)}${Js(o)}${Js(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(Qi||(Qi={}));var AE;(e=>{function t(p,d){if(ri=(d.rgba&255)/255,ri===1)return{css:d.css,rgba:d.rgba};let x=d.rgba>>24&255,_=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,E=p.rgba>>8&255;Oi=v+Math.round((x-v)*ri),zi=y+Math.round((_-y)*ri),Pi=E+Math.round((b-E)*ri);let A=Qi.toCss(Oi,zi,Pi),N=Qi.toRgba(Oi,zi,Pi);return{css:A,rgba:N}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,x){let _=_u.ensureContrastRatio(p.rgba,d.rgba,x);if(_)return Qi.toColor(_>>24&255,_>>16&255,_>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[Oi,zi,Pi]=_u.toChannels(d),{css:Qi.toCss(Oi,zi,Pi),rgba:d}}e.opaque=a;function o(p,d){return ri=Math.round(d*255),[Oi,zi,Pi]=_u.toChannels(p.rgba),{css:Qi.toCss(Oi,zi,Pi,ri),rgba:Qi.toRgba(Oi,zi,Pi,ri)}}e.opacity=o;function c(p,d){return ri=p.rgba&255,o(p,ri*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(AE||(AE={}));var Wi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Oi=parseInt(a.slice(1,2).repeat(2),16),zi=parseInt(a.slice(2,3).repeat(2),16),Pi=parseInt(a.slice(3,4).repeat(2),16),Qi.toColor(Oi,zi,Pi);case 5:return Oi=parseInt(a.slice(1,2).repeat(2),16),zi=parseInt(a.slice(2,3).repeat(2),16),Pi=parseInt(a.slice(3,4).repeat(2),16),ri=parseInt(a.slice(4,5).repeat(2),16),Qi.toColor(Oi,zi,Pi,ri);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Oi=parseInt(o[1]),zi=parseInt(o[2]),Pi=parseInt(o[3]),ri=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Qi.toColor(Oi,zi,Pi,ri);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Oi,zi,Pi,ri]=t.getImageData(0,0,1,1).data,ri!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Qi.toRgba(Oi,zi,Pi,ri),css:a}}e.toColor=s})(Wi||(Wi={}));var cn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),x=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),_=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+x*.7152+_*.0722}e.relativeLuminance2=i})(cn||(cn={}));var _u;(e=>{function t(c,h){if(ri=(h&255)/255,ri===1)return h;let p=h>>24&255,d=h>>16&255,x=h>>8&255,_=c>>24&255,b=c>>16&255,v=c>>8&255;return Oi=_+Math.round((p-_)*ri),zi=b+Math.round((d-b)*ri),Pi=v+Math.round((x-v)*ri),Qi.toRgba(Oi,zi,Pi)}e.blend=t;function i(c,h,p){let d=cn.relativeLuminance(c>>8),x=cn.relativeLuminance(h>>8);if(Kr(d,x)>8));if(y>8));return y>A?v:E}return v}let _=a(c,h,p),b=Kr(d,cn.relativeLuminance(_>>8));if(b>8));return b>y?_:v}return _}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,x=c>>16&255,_=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,E=Kr(cn.relativeLuminance2(b,v,y),cn.relativeLuminance2(d,x,_));for(;E0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),E=Kr(cn.relativeLuminance2(b,v,y),cn.relativeLuminance2(d,x,_));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,x=c>>16&255,_=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,E=Kr(cn.relativeLuminance2(b,v,y),cn.relativeLuminance2(d,x,_));for(;E>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(_u||(_u={}));function Js(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Kr(e,t){return e{let e=[Wi.toColor("#2e3436"),Wi.toColor("#cc0000"),Wi.toColor("#4e9a06"),Wi.toColor("#c4a000"),Wi.toColor("#3465a4"),Wi.toColor("#75507b"),Wi.toColor("#06989a"),Wi.toColor("#d3d7cf"),Wi.toColor("#555753"),Wi.toColor("#ef2929"),Wi.toColor("#8ae234"),Wi.toColor("#fce94f"),Wi.toColor("#729fcf"),Wi.toColor("#ad7fa8"),Wi.toColor("#34e2e2"),Wi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Qi.toCss(s,a,o),rgba:Qi.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Qi.toCss(s,s,s),rgba:Qi.toRgba(s,s,s)})}return e})());function Jb(e,t,i){return Math.max(t,Math.min(e,i))}function ME(e){switch(e){case"&":return"&";case"<":return"<"}return e}var d0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let d=o;d<=c;d++){let x=this._buffer.getLine(d);if(x){let _=d===e.start.y?h:0,b=d===e.end.y?p:x.length;for(let v=_;v0&&!Vr(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r -`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),d=p.getWidth()>1,x=!1;(p.getChars()&&d?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&Vr(c,p)&&(x=!0),d&&(h.getChars()||h.getWidth()===0)&&Vr(c,p)&&Vr(h,p)&&(x=!0)),x||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!f0(e,t),a=!Vr(e,t),o=!p0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!Vr(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{d>0?i+=`\x1B[${d}C`:d<0&&(i+=`\x1B[${-d}D`)};h&&((d=>{d>0?i+=`\x1B[${d}B`:d<0&&(i+=`\x1B[${-d}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},BE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:Jb(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new DE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new LE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,d=t.scrollback,x=d===void 0?p:Jb(d+e.rows,0,p);return s.serialize({start:{x:0,y:p-x},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},LE=class extends d0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=RE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!f0(e,t),a=!Vr(e,t),o=!p0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"":""),a?this._currentRow+=" ":this._currentRow+=ME(e.getChars())}_serializeString(){return this._htmlContent}};const OE="__OWS_FRESH_SESSION__",Za="[REDACTED]",zE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${Za}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${Za}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${Za}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${Za}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${Za}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${Za}`]];function ev(e){let t=e;for(const[i,s]of zE)t=t.replace(i,s);return t}const tv="codex features enable image_generation";function PE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const IE={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},HE="plotlink-terminal",UE=1,Ds="scrollback",iv=10*1024*1024;function Kp(){return new Promise((e,t)=>{const i=indexedDB.open(HE,UE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ds)||s.createObjectStore(Ds)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Qa(e,t){const i=t.length>iv?t.slice(-iv):t,s=await Kp();return new Promise((a,o)=>{const c=s.transaction(Ds,"readwrite");c.objectStore(Ds).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function $E(e){const t=await Kp();return new Promise((i,s)=>{const o=t.transaction(Ds,"readonly").objectStore(Ds).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function hf(e){const t=await Kp();return new Promise((i,s)=>{const a=t.transaction(Ds,"readwrite");a.objectStore(Ds).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const ji=new Map;function FE({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:d,readiness:x,contentType:_,needsProviderRepair:b,onRepairProvider:v}){const y=w.useRef(null),E=w.useRef(i),[A,N]=w.useState([]),[L,O]=w.useState(new Set),[J,$]=w.useState(null),[M,X]=w.useState(null),[he,ye]=w.useState(!1),[U,se]=w.useState(!1),W=PE(_,x),G=!!b,Z=w.useRef(()=>{});w.useEffect(()=>{E.current=i},[i]);const I=w.useCallback(F=>{var be;const{width:ue}=F.container.getBoundingClientRect();if(!(ue<50))try{F.fit.fit(),((be=F.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&F.ws.send(JSON.stringify({type:"resize",cols:F.term.cols,rows:F.term.rows}))}catch{}},[]),j=w.useCallback(F=>{for(const[ue,be]of ji)be.container.style.display=ue===F?"block":"none";if(F){const ue=ji.get(F);ue&&setTimeout(()=>I(ue),50)}},[I]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const B=w.useRef({});w.useEffect(()=>{B.current=d||{}},[d]);const _e=w.useCallback((F,ue,be)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",Ee=z.current[F]?"&bypass=true":"",Be=B.current[F],je=Be?`&provider=${encodeURIComponent(Be)}`:"",Ze=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent(F)}&token=${e}&resume=${be}${Ee}${je}`);Ze.onopen=()=>{ue.connected=!0,ue._retried=!1,O(tt=>{const mt=new Set(tt);return mt.delete(F),mt}),Ze.send(JSON.stringify({type:"resize",cols:ue.term.cols,rows:ue.term.rows}))};let we=!0;Ze.onmessage=tt=>{if(we&&(we=!1,typeof tt.data=="string"&&tt.data===OE)){ue.term.reset(),hf(F).catch(()=>{});return}ue.term.write(typeof tt.data=="string"?ev(tt.data):tt.data)},Ze.onclose=tt=>{if(ue.connected=!1,ue.ws===Ze){ue.ws=null;try{const mt=ue.serialize.serialize();Qa(F,mt).catch(()=>{})}catch{}if(tt.code===4e3&&!ue._retried){ue._retried=!0,ue.term.write(`\r + */var zi=0,Pi=0,Ii=0,li=0,tn;(e=>{function t(a,o,c,h){return h!==void 0?`#${Js(a)}${Js(o)}${Js(c)}${Js(h)}`:`#${Js(a)}${Js(o)}${Js(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(tn||(tn={}));var ME;(e=>{function t(p,d){if(li=(d.rgba&255)/255,li===1)return{css:d.css,rgba:d.rgba};let _=d.rgba>>24&255,x=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,N=p.rgba>>8&255;zi=v+Math.round((_-v)*li),Pi=y+Math.round((x-y)*li),Ii=N+Math.round((b-N)*li);let A=tn.toCss(zi,Pi,Ii),E=tn.toRgba(zi,Pi,Ii);return{css:A,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,_){let x=xu.ensureContrastRatio(p.rgba,d.rgba,_);if(x)return tn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[zi,Pi,Ii]=xu.toChannels(d),{css:tn.toCss(zi,Pi,Ii),rgba:d}}e.opaque=a;function o(p,d){return li=Math.round(d*255),[zi,Pi,Ii]=xu.toChannels(p.rgba),{css:tn.toCss(zi,Pi,Ii,li),rgba:tn.toRgba(zi,Pi,Ii,li)}}e.opacity=o;function c(p,d){return li=p.rgba&255,o(p,li*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ME||(ME={}));var Yi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return zi=parseInt(a.slice(1,2).repeat(2),16),Pi=parseInt(a.slice(2,3).repeat(2),16),Ii=parseInt(a.slice(3,4).repeat(2),16),tn.toColor(zi,Pi,Ii);case 5:return zi=parseInt(a.slice(1,2).repeat(2),16),Pi=parseInt(a.slice(2,3).repeat(2),16),Ii=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),tn.toColor(zi,Pi,Ii,li);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return zi=parseInt(o[1]),Pi=parseInt(o[2]),Ii=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),tn.toColor(zi,Pi,Ii,li);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[zi,Pi,Ii,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:tn.toRgba(zi,Pi,Ii,li),css:a}}e.toColor=s})(Yi||(Yi={}));var hn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var xu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,d=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return zi=x+Math.round((p-x)*li),Pi=b+Math.round((d-b)*li),Ii=v+Math.round((_-v)*li),tn.toRgba(zi,Pi,Ii)}e.blend=t;function i(c,h,p){let d=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Kr(d,_)>8));if(y>8));return y>A?v:N}return v}let x=a(c,h,p),b=Kr(d,hn.relativeLuminance(x>>8));if(b>8));return b>y?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(xu||(xu={}));function Js(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Kr(e,t){return e{let e=[Yi.toColor("#2e3436"),Yi.toColor("#cc0000"),Yi.toColor("#4e9a06"),Yi.toColor("#c4a000"),Yi.toColor("#3465a4"),Yi.toColor("#75507b"),Yi.toColor("#06989a"),Yi.toColor("#d3d7cf"),Yi.toColor("#555753"),Yi.toColor("#ef2929"),Yi.toColor("#8ae234"),Yi.toColor("#fce94f"),Yi.toColor("#729fcf"),Yi.toColor("#ad7fa8"),Yi.toColor("#34e2e2"),Yi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:tn.toCss(s,a,o),rgba:tn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:tn.toCss(s,s,s),rgba:tn.toRgba(s,s,s)})}return e})());function ev(e,t,i){return Math.max(t,Math.min(e,i))}function BE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var f0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let d=o;d<=c;d++){let _=this._buffer.getLine(d);if(_){let x=d===e.start.y?h:0,b=d===e.end.y?p:_.length;for(let v=x;v0&&!Vr(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r +`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),d=p.getWidth()>1,_=!1;(p.getChars()&&d?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&Vr(c,p)&&(_=!0),d&&(h.getChars()||h.getWidth()===0)&&Vr(c,p)&&Vr(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!p0(e,t),a=!Vr(e,t),o=!m0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!Vr(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{d>0?i+=`\x1B[${d}C`:d<0&&(i+=`\x1B[${-d}D`)};h&&((d=>{d>0?i+=`\x1B[${d}B`:d<0&&(i+=`\x1B[${-d}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},OE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:ev(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new LE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new zE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,d=t.scrollback,_=d===void 0?p:ev(d+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},zE=class extends f0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=DE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!p0(e,t),a=!Vr(e,t),o=!m0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),a?this._currentRow+=" ":this._currentRow+=BE(e.getChars())}_serializeString(){return this._htmlContent}};const PE="__OWS_FRESH_SESSION__",Xa="[REDACTED]",IE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${Xa}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${Xa}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${Xa}`]];function tv(e){let t=e;for(const[i,s]of IE)t=t.replace(i,s);return t}const iv="codex features enable image_generation";function HE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const UE={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},$E="plotlink-terminal",FE=1,Ds="scrollback",nv=10*1024*1024;function Kp(){return new Promise((e,t)=>{const i=indexedDB.open($E,FE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ds)||s.createObjectStore(Ds)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Za(e,t){const i=t.length>nv?t.slice(-nv):t,s=await Kp();return new Promise((a,o)=>{const c=s.transaction(Ds,"readwrite");c.objectStore(Ds).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function qE(e){const t=await Kp();return new Promise((i,s)=>{const o=t.transaction(Ds,"readonly").objectStore(Ds).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function hf(e){const t=await Kp();return new Promise((i,s)=>{const a=t.transaction(Ds,"readwrite");a.objectStore(Ds).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ai=new Map;function WE({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:d,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const y=w.useRef(null),N=w.useRef(i),[A,E]=w.useState([]),[D,P]=w.useState(new Set),[J,q]=w.useState(null),[L,Z]=w.useState(null),[he,ye]=w.useState(!1),[U,re]=w.useState(!1),W=HE(x,_),G=!!b,X=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const I=w.useCallback($=>{var be;const{width:ue}=$.container.getBoundingClientRect();if(!(ue<50))try{$.fit.fit(),((be=$.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&$.ws.send(JSON.stringify({type:"resize",cols:$.term.cols,rows:$.term.rows}))}catch{}},[]),j=w.useCallback($=>{for(const[ue,be]of Ai)be.container.style.display=ue===$?"block":"none";if($){const ue=Ai.get($);ue&&setTimeout(()=>I(ue),50)}},[I]),O=w.useRef({});w.useEffect(()=>{O.current=p||{}},[p]);const B=w.useRef({});w.useEffect(()=>{B.current=d||{}},[d]);const xe=w.useCallback(($,ue,be)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",Ee=O.current[$]?"&bypass=true":"",Be=B.current[$],je=Be?`&provider=${encodeURIComponent(Be)}`:"",Ze=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent($)}&token=${e}&resume=${be}${Ee}${je}`);Ze.onopen=()=>{ue.connected=!0,ue._retried=!1,P(tt=>{const pt=new Set(tt);return pt.delete($),pt}),Ze.send(JSON.stringify({type:"resize",cols:ue.term.cols,rows:ue.term.rows}))};let Ce=!0;Ze.onmessage=tt=>{if(Ce&&(Ce=!1,typeof tt.data=="string"&&tt.data===PE)){ue.term.reset(),hf($).catch(()=>{});return}ue.term.write(typeof tt.data=="string"?tv(tt.data):tt.data)},Ze.onclose=tt=>{if(ue.connected=!1,ue.ws===Ze){ue.ws=null;try{const pt=ue.serialize.serialize();Za($,pt).catch(()=>{})}catch{}if(tt.code===4e3&&!ue._retried){ue._retried=!0,ue.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),Z.current(F,ue,!1);return}O(mt=>new Set(mt).add(F))}},ue.term.onData(tt=>{Ze.readyState===WebSocket.OPEN&&Ze.send(tt)}),ue.ws=Ze},[e]);w.useEffect(()=>{Z.current=_e},[_e]);const T=w.useCallback(async(F,ue)=>{if(!y.current||ji.has(F))return;const{resume:be=!1,autoConnect:De=!0}=ue??{},Ee=document.createElement("div");Ee.style.width="100%",Ee.style.height="100%",Ee.style.display="none",Ee.style.paddingLeft="10px",Ee.style.boxSizing="border-box",y.current.appendChild(Ee);const Be=new EE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:IE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),je=new jE,Ze=new BE;Be.loadAddon(je),Be.loadAddon(Ze),Be.open(Ee);const we={term:Be,fit:je,serialize:Ze,ws:null,container:Ee,observer:null,connected:!1},tt=new ResizeObserver(()=>{var Ge;const{width:mt}=Ee.getBoundingClientRect();if(!(mt<50))try{je.fit(),((Ge=we.ws)==null?void 0:Ge.readyState)===WebSocket.OPEN&&we.ws.send(JSON.stringify({type:"resize",cols:Be.cols,rows:Be.rows}))}catch{}});tt.observe(Ee),we.observer=tt,ji.set(F,we),N(mt=>[...mt,F]);try{const mt=await $E(F);if(mt){const Ge=ev(mt);Be.write(Ge),Ge!==mt&&Qa(F,Ge).catch(()=>{})}}catch{}De?_e(F,we,be):O(mt=>new Set(mt).add(F)),setTimeout(()=>I(we),50)},[_e,I]),R=w.useCallback(async(F,ue)=>{const be=ji.get(F);be&&(be.ws&&(be.ws.close(),be.ws=null),ue||(await E.current(`/api/terminal/${encodeURIComponent(F)}`,{method:"DELETE"}).catch(()=>{}),be.term.clear()),_e(F,be,ue))},[_e]),Y=w.useCallback(F=>{const ue=ji.get(F);if(ue){try{const be=ue.serialize.serialize();Qa(F,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),ji.delete(F),N(be=>be.filter(De=>De!==F)),O(be=>{const De=new Set(be);return De.delete(F),De}),i(`/api/terminal/${encodeURIComponent(F)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(F)}},[i,a]),C=w.useCallback(F=>{var be;const ue=ji.get(F);ue&&(((be=ue.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&ue.ws.send(`exit -`),hf(F).catch(()=>{}),ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),ji.delete(F),N(De=>De.filter(Ee=>Ee!==F)),O(De=>{const Ee=new Set(De);return Ee.delete(F),Ee}),i(`/api/terminal/${encodeURIComponent(F)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(F))},[i,a]),ae=w.useCallback(async(F,ue,be)=>{const De=ji.get(F);if(!De||ji.has(ue)||!(await E.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:F,newName:ue,...be??{}})})).ok)return!1;ji.delete(F),ji.set(ue,De);try{const Be=De.serialize.serialize();await hf(F),await Qa(ue,Be)}catch{}return N(Be=>Be.map(je=>je===F?ue:je)),O(Be=>{if(!Be.has(F))return Be;const je=new Set(Be);return je.delete(F),je.add(ue),je}),(De.connected||De.ws)&&(await E.current(`/api/terminal/${encodeURIComponent(ue)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),Z.current(ue,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=ae),()=>{h&&(h.current=null)}),[h,ae]),w.useEffect(()=>{if(t){if(W){j(null);return}if(G){j(null);return}ji.has(t)?j(t):E.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(F=>F.ok?F.json():null).then(F=>{if(!ji.has(t)){const ue=(F==null?void 0:F.sessionId)&&!(F!=null&&F.running);T(t,{autoConnect:!ue}),j(t)}}).catch(()=>{ji.has(t)||(T(t),j(t))})}},[t,T,j,W,G]),w.useEffect(()=>{const F=setInterval(()=>{for(const[ue,be]of ji)if(be.connected)try{const De=be.serialize.serialize();Qa(ue,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval(F)},[]),w.useEffect(()=>()=>{for(const[F,ue]of ji){try{const be=ue.serialize.serialize();Qa(F,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),E.current(`/api/terminal/${encodeURIComponent(F)}`,{method:"DELETE"}).catch(()=>{})}ji.clear()},[]);const ie=t?L.has(t):!1,oe=A.length===0;return f.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&f.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[A.map(F=>f.jsxs("div",{onClick:()=>s==null?void 0:s(F),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${F===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[f.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L.has(F)?"bg-amber-500":F===t?"bg-green-600":"bg-muted/50"}`}),f.jsx("span",{className:`truncate max-w-[120px] ${F.startsWith("_new_")?"italic":""}`,children:F.startsWith("_new_")?"Untitled":F}),f.jsx("button",{onClick:ue=>{ue.stopPropagation(),F.startsWith("_new_")?$(F):Y(F)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},F)),t!=null&&t.startsWith("_new_")?f.jsx("button",{onClick:()=>$(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?f.jsx("button",{onClick:()=>X(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),f.jsxs("div",{className:"relative flex-1 min-h-0",children:[f.jsx("div",{ref:y,className:"h-full"}),oe&&!W&&!G&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),f.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),W&&f.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),f.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),x&&!x.codex.installed?f.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Su(x)?f.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[zp," Then reopen this story."]}):f.jsxs("div",{className:"space-y-1",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:tv}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(tv),ye(!0),setTimeout(()=>ye(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:he?"Copied!":"Copy"})]})]})]})}),G&&!W&&f.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),f.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),f.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),f.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:U,onClick:async()=>{if(!U){se(!0);try{await(v==null?void 0:v())}finally{se(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:U?"Setting…":"Set this story's provider to Codex"})]})}),J&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),f.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>$(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:()=>{const F=J;$(null),C(F)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),M&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),f.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>X(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:async()=>{const F=M;X(null);try{(await E.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:F})})).ok&&(Y(F),o==null||o(F))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ie&&t&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>R(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),f.jsx("button",{onClick:()=>R(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),f.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function qE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const WE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,GE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,YE={};function nv(e,t){return(YE.jsx?GE:WE).test(e)}const KE=/[ \t\n\f\r]/g;function VE(e){return typeof e=="object"?e.type==="text"?rv(e.value):!1:rv(e)}function rv(e){return e.replace(KE,"")===""}class Bo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Bo.prototype.normal={};Bo.prototype.property={};Bo.prototype.space=void 0;function m0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Bo(i,s,t)}function vp(e){return e.toLowerCase()}class Cn{constructor(t,i){this.attribute=i,this.property=t}}Cn.prototype.attribute="";Cn.prototype.booleanish=!1;Cn.prototype.boolean=!1;Cn.prototype.commaOrSpaceSeparated=!1;Cn.prototype.commaSeparated=!1;Cn.prototype.defined=!1;Cn.prototype.mustUseProperty=!1;Cn.prototype.number=!1;Cn.prototype.overloadedBoolean=!1;Cn.prototype.property="";Cn.prototype.spaceSeparated=!1;Cn.prototype.space=void 0;let XE=0;const lt=ua(),yi=ua(),yp=ua(),ve=ua(),Wt=ua(),nl=ua(),On=ua();function ua(){return 2**++XE}const Sp=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:yi,commaOrSpaceSeparated:On,commaSeparated:nl,number:ve,overloadedBoolean:yp,spaceSeparated:Wt},Symbol.toStringTag,{value:"Module"})),df=Object.keys(Sp);class Vp extends Cn{constructor(t,i,s,a){let o=-1;if(super(t,i),sv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&tN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(av,rN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!av.test(o)){let c=o.replace(eN,nN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Vp}return new a(s,t)}function nN(e){return"-"+e.toLowerCase()}function rN(e){return e.charAt(1).toUpperCase()}const sN=m0([g0,ZE,b0,v0,y0],"html"),Xp=m0([g0,QE,b0,v0,y0],"svg");function aN(e){return e.join(" ").trim()}var Ja={},ff,lv;function lN(){if(lv)return ff;lv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` -`,d="/",x="*",_="",b="comment",v="declaration";function y(A,N){if(typeof A!="string")throw new TypeError("First argument must be a string");if(!A)return[];N=N||{};var L=1,O=1;function J(Z){var I=Z.match(t);I&&(L+=I.length);var j=Z.lastIndexOf(p);O=~j?Z.length-j:O+Z.length}function $(){var Z={line:L,column:O};return function(I){return I.position=new M(Z),ye(),I}}function M(Z){this.start=Z,this.end={line:L,column:O},this.source=N.source}M.prototype.content=A;function X(Z){var I=new Error(N.source+":"+L+":"+O+": "+Z);if(I.reason=Z,I.filename=N.source,I.line=L,I.column=O,I.source=A,!N.silent)throw I}function he(Z){var I=Z.exec(A);if(I){var j=I[0];return J(j),A=A.slice(j.length),I}}function ye(){he(i)}function U(Z){var I;for(Z=Z||[];I=se();)I!==!1&&Z.push(I);return Z}function se(){var Z=$();if(!(d!=A.charAt(0)||x!=A.charAt(1))){for(var I=2;_!=A.charAt(I)&&(x!=A.charAt(I)||d!=A.charAt(I+1));)++I;if(I+=2,_===A.charAt(I-1))return X("End of comment missing");var j=A.slice(2,I-2);return O+=2,J(j),A=A.slice(I),O+=2,Z({type:b,comment:j})}}function W(){var Z=$(),I=he(s);if(I){if(se(),!he(a))return X("property missing ':'");var j=he(o),z=Z({type:v,property:E(I[0].replace(e,_)),value:j?E(j[0].replace(e,_)):_});return he(c),z}}function G(){var Z=[];U(Z);for(var I;I=W();)I!==!1&&(Z.push(I),U(Z));return Z}return ye(),G()}function E(A){return A?A.replace(h,_):_}return ff=y,ff}var ov;function oN(){if(ov)return Ja;ov=1;var e=Ja&&Ja.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.default=i;const t=e(lN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:d,value:x}=p;h?a(d,x,p):x&&(o=o||{},o[d]=x)}),o}return Ja}var co={},cv;function cN(){if(cv)return co;cv=1,Object.defineProperty(co,"__esModule",{value:!0}),co.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(d){return!d||i.test(d)||e.test(d)},c=function(d,x){return x.toUpperCase()},h=function(d,x){return"".concat(x,"-")},p=function(d,x){return x===void 0&&(x={}),o(d)?d:(d=d.toLowerCase(),x.reactCompat?d=d.replace(a,h):d=d.replace(s,h),d.replace(t,c))};return co.camelCase=p,co}var uo,uv;function uN(){if(uv)return uo;uv=1;var e=uo&&uo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(oN()),i=cN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,uo=s,uo}var hN=uN();const dN=Du(hN),S0=w0("end"),Zp=w0("start");function w0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function C0(e){const t=Zp(e),i=S0(e);if(t&&i)return{start:t,end:i}}function vo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?hv(e.position):"start"in e||"end"in e?hv(e):"line"in e||"column"in e?wp(e):""}function wp(e){return dv(e&&e.line)+":"+dv(e&&e.column)}function hv(e){return wp(e&&e.start)+"-"+wp(e&&e.end)}function dv(e){return e&&typeof e=="number"?e:1}class en extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=vo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}en.prototype.file="";en.prototype.name="";en.prototype.reason="";en.prototype.message="";en.prototype.stack="";en.prototype.column=void 0;en.prototype.line=void 0;en.prototype.ancestors=void 0;en.prototype.cause=void 0;en.prototype.fatal=void 0;en.prototype.place=void 0;en.prototype.ruleId=void 0;en.prototype.source=void 0;const Qp={}.hasOwnProperty,fN=new Map,pN=/[A-Z]/g,mN=new Set(["table","tbody","thead","tfoot","tr"]),gN=new Set(["td","th"]),k0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function _N(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=kN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=CN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Xp:sN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=E0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function E0(e,t,i){if(t.type==="element")return xN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return bN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return yN(e,t,i);if(t.type==="mdxjsEsm")return vN(e,t);if(t.type==="root")return SN(e,t,i);if(t.type==="text")return wN(e,t)}function xN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=T0(e,t.tagName,!1),c=EN(e,t);let h=em(e,t);return mN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!VE(p):!0})),N0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function bN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Eo(e,t.position)}function vN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Eo(e,t.position)}function yN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:T0(e,t.name,!0),c=NN(e,t),h=em(e,t);return N0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function SN(e,t,i){const s={};return Jp(s,em(e,t)),e.create(t,e.Fragment,s,i)}function wN(e,t){return t.value}function N0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function Jp(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function CN(e,t,i){return s;function s(a,o,c,h){const d=Array.isArray(c.children)?i:t;return h?d(o,c,h):d(o,c)}}function kN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=Zp(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function EN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&Qp.call(t.properties,a)){const o=TN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&gN.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function NN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Eo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Eo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function em(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:fN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(zn(e,e.length,0,t),e):t}const mv={}.hasOwnProperty;function A0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function dr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const un=Bs(/[A-Za-z]/),Ji=Bs(/[\dA-Za-z]/),zN=Bs(/[#-'*+\--9=?A-Z^-~]/);function ju(e){return e!==null&&(e<32||e===127)}const Cp=Bs(/\d/),PN=Bs(/[\dA-Fa-f]/),IN=Bs(/[!-/:-@[-`{-~]/);function $e(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function xt(e){return e===-2||e===-1||e===32}const Pu=Bs(new RegExp("\\p{P}|\\p{S}","u")),oa=Bs(/\s/);function Bs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function dl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function Ct(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return xt(p)?(e.enter(i),h(p)):t(p)}function h(p){return xt(p)&&o++c))return;const X=t.events.length;let he=X,ye,U;for(;he--;)if(t.events[he][0]==="exit"&&t.events[he][1].type==="chunkFlow"){if(ye){U=t.events[he][1].end;break}ye=!0}for(N(s),M=X;MO;){const $=i[J];t.containerState=$[1],$[0].exit.call(t,e)}i.length=O}function L(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function qN(e,t,i){return Ct(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ll(e){if(e===null||qt(e)||oa(e))return 1;if(Pu(e))return 2}function Iu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const _={...e[s][1].end},b={...e[i][1].start};_v(_,-p),_v(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:_,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},d=[],e[s][1].end.offset-e[s][1].start.offset&&(d=tr(d,[["enter",e[s][1],t],["exit",e[s][1],t]])),d=tr(d,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),d=tr(d,Iu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),d=tr(d,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(x=2,d=tr(d,[["enter",e[i][1],t],["exit",e[i][1],t]])):x=0,zn(e,s-1,i-s+3,d),i=s+d.length-x-2;break}}for(i=-1;++i0&&xt(M)?Ct(e,L,"linePrefix",o+1)(M):L(M)}function L(M){return M===null||$e(M)?e.check(xv,E,J)(M):(e.enter("codeFlowValue"),O(M))}function O(M){return M===null||$e(M)?(e.exit("codeFlowValue"),L(M)):(e.consume(M),O)}function J(M){return e.exit("codeFenced"),t(M)}function $(M,X,he){let ye=0;return U;function U(I){return M.enter("lineEnding"),M.consume(I),M.exit("lineEnding"),se}function se(I){return M.enter("codeFencedFence"),xt(I)?Ct(M,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(M.enter("codeFencedFenceSequence"),G(I)):he(I)}function G(I){return I===h?(ye++,M.consume(I),G):ye>=c?(M.exit("codeFencedFenceSequence"),xt(I)?Ct(M,Z,"whitespace")(I):Z(I)):he(I)}function Z(I){return I===null||$e(I)?(M.exit("codeFencedFence"),X(I)):he(I)}}}function i5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const mf={name:"codeIndented",tokenize:r5},n5={partial:!0,tokenize:s5};function r5(e,t,i){const s=this;return a;function a(d){return e.enter("codeIndented"),Ct(e,o,"linePrefix",5)(d)}function o(d){const x=s.events[s.events.length-1];return x&&x[1].type==="linePrefix"&&x[2].sliceSerialize(x[1],!0).length>=4?c(d):i(d)}function c(d){return d===null?p(d):$e(d)?e.attempt(n5,c,p)(d):(e.enter("codeFlowValue"),h(d))}function h(d){return d===null||$e(d)?(e.exit("codeFlowValue"),c(d)):(e.consume(d),h)}function p(d){return e.exit("codeIndented"),t(d)}}function s5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):$e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):Ct(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):$e(c)?a(c):i(c)}}const a5={name:"codeText",previous:o5,resolve:l5,tokenize:c5};function l5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&ho(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ho(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function O0(e,t,i,s,a,o,c,h,p){const d=p||Number.POSITIVE_INFINITY;let x=0;return _;function _(N){return N===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(N),e.exit(o),b):N===null||N===32||N===41||ju(N)?i(N):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),E(N))}function b(N){return N===62?(e.enter(o),e.consume(N),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(N))}function v(N){return N===62?(e.exit("chunkString"),e.exit(h),b(N)):N===null||N===60||$e(N)?i(N):(e.consume(N),N===92?y:v)}function y(N){return N===60||N===62||N===92?(e.consume(N),v):v(N)}function E(N){return!x&&(N===null||N===41||qt(N))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(N)):x999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):$e(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),x):(e.enter("chunkString",{contentType:"string"}),_(v))}function _(v){return v===null||v===91||v===93||$e(v)||h++>999?(e.exit("chunkString"),x(v)):(e.consume(v),p||(p=!xt(v)),v===92?b:_)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,_):_(v)}}function P0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),d(b))}function d(b){return b===c?(e.exit(o),p(c)):b===null?i(b):$e(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),Ct(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),x(b))}function x(b){return b===c||b===null||$e(b)?(e.exit("chunkString"),d(b)):(e.consume(b),b===92?_:x)}function _(b){return b===c||b===92?(e.consume(b),x):x(b)}}function yo(e,t){let i;return s;function s(a){return $e(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?Ct(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const _5={name:"definition",tokenize:b5},x5={partial:!0,tokenize:v5};function b5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return z0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=dr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?yo(e,d)(v):d(v)}function d(v){return O0(e,x,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function x(v){return e.attempt(x5,_,_)(v)}function _(v){return xt(v)?Ct(e,b,"whitespace")(v):b(v)}function b(v){return v===null||$e(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function v5(e,t,i){return s;function s(h){return qt(h)?yo(e,a)(h):i(h)}function a(h){return P0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?Ct(e,c,"whitespace")(h):c(h)}function c(h){return h===null||$e(h)?t(h):i(h)}}const y5={name:"hardBreakEscape",tokenize:S5};function S5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return $e(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const w5={name:"headingAtx",resolve:C5,tokenize:k5};function C5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},zn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function k5(e,t,i){let s=0;return a;function a(x){return e.enter("atxHeading"),o(x)}function o(x){return e.enter("atxHeadingSequence"),c(x)}function c(x){return x===35&&s++<6?(e.consume(x),c):x===null||qt(x)?(e.exit("atxHeadingSequence"),h(x)):i(x)}function h(x){return x===35?(e.enter("atxHeadingSequence"),p(x)):x===null||$e(x)?(e.exit("atxHeading"),t(x)):xt(x)?Ct(e,h,"whitespace")(x):(e.enter("atxHeadingText"),d(x))}function p(x){return x===35?(e.consume(x),p):(e.exit("atxHeadingSequence"),h(x))}function d(x){return x===null||x===35||qt(x)?(e.exit("atxHeadingText"),h(x)):(e.consume(x),d)}}const E5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],vv=["pre","script","style","textarea"],N5={concrete:!0,name:"htmlFlow",resolveTo:A5,tokenize:R5},T5={partial:!0,tokenize:D5},j5={partial:!0,tokenize:M5};function A5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function R5(e,t,i){const s=this;let a,o,c,h,p;return d;function d(C){return x(C)}function x(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),_}function _(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,E):C===63?(e.consume(C),a=3,s.interrupt?t:T):un(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,y):un(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function y(C){const ae="CDATA[";return C===ae.charCodeAt(h++)?(e.consume(C),h===ae.length?s.interrupt?t:W:y):i(C)}function E(C){return un(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function A(C){if(C===null||C===47||C===62||qt(C)){const ae=C===47,ie=c.toLowerCase();return!ae&&!o&&vv.includes(ie)?(a=1,s.interrupt?t(C):W(C)):E5.includes(c.toLowerCase())?(a=6,ae?(e.consume(C),N):s.interrupt?t(C):W(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?L(C):O(C))}return C===45||Ji(C)?(e.consume(C),c+=String.fromCharCode(C),A):i(C)}function N(C){return C===62?(e.consume(C),s.interrupt?t:W):i(C)}function L(C){return xt(C)?(e.consume(C),L):U(C)}function O(C){return C===47?(e.consume(C),U):C===58||C===95||un(C)?(e.consume(C),J):xt(C)?(e.consume(C),O):U(C)}function J(C){return C===45||C===46||C===58||C===95||Ji(C)?(e.consume(C),J):$(C)}function $(C){return C===61?(e.consume(C),M):xt(C)?(e.consume(C),$):O(C)}function M(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,X):xt(C)?(e.consume(C),M):he(C)}function X(C){return C===p?(e.consume(C),p=null,ye):C===null||$e(C)?i(C):(e.consume(C),X)}function he(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?$(C):(e.consume(C),he)}function ye(C){return C===47||C===62||xt(C)?O(C):i(C)}function U(C){return C===62?(e.consume(C),se):i(C)}function se(C){return C===null||$e(C)?W(C):xt(C)?(e.consume(C),se):i(C)}function W(C){return C===45&&a===2?(e.consume(C),j):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),R):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),_e):$e(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(T5,Y,G)(C)):C===null||$e(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),W)}function G(C){return e.check(j5,Z,Y)(C)}function Z(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),I}function I(C){return C===null||$e(C)?G(C):(e.enter("htmlFlowData"),W(C))}function j(C){return C===45?(e.consume(C),T):W(C)}function z(C){return C===47?(e.consume(C),c="",B):W(C)}function B(C){if(C===62){const ae=c.toLowerCase();return vv.includes(ae)?(e.consume(C),R):W(C)}return un(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),B):W(C)}function _e(C){return C===93?(e.consume(C),T):W(C)}function T(C){return C===62?(e.consume(C),R):C===45&&a===2?(e.consume(C),T):W(C)}function R(C){return C===null||$e(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),R)}function Y(C){return e.exit("htmlFlow"),t(C)}}function M5(e,t,i){const s=this;return a;function a(c){return $e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function D5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Lo,t,i)}}const B5={name:"htmlText",tokenize:L5};function L5(e,t,i){const s=this;let a,o,c;return h;function h(T){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(T),p}function p(T){return T===33?(e.consume(T),d):T===47?(e.consume(T),$):T===63?(e.consume(T),O):un(T)?(e.consume(T),he):i(T)}function d(T){return T===45?(e.consume(T),x):T===91?(e.consume(T),o=0,y):un(T)?(e.consume(T),L):i(T)}function x(T){return T===45?(e.consume(T),v):i(T)}function _(T){return T===null?i(T):T===45?(e.consume(T),b):$e(T)?(c=_,z(T)):(e.consume(T),_)}function b(T){return T===45?(e.consume(T),v):_(T)}function v(T){return T===62?j(T):T===45?b(T):_(T)}function y(T){const R="CDATA[";return T===R.charCodeAt(o++)?(e.consume(T),o===R.length?E:y):i(T)}function E(T){return T===null?i(T):T===93?(e.consume(T),A):$e(T)?(c=E,z(T)):(e.consume(T),E)}function A(T){return T===93?(e.consume(T),N):E(T)}function N(T){return T===62?j(T):T===93?(e.consume(T),N):E(T)}function L(T){return T===null||T===62?j(T):$e(T)?(c=L,z(T)):(e.consume(T),L)}function O(T){return T===null?i(T):T===63?(e.consume(T),J):$e(T)?(c=O,z(T)):(e.consume(T),O)}function J(T){return T===62?j(T):O(T)}function $(T){return un(T)?(e.consume(T),M):i(T)}function M(T){return T===45||Ji(T)?(e.consume(T),M):X(T)}function X(T){return $e(T)?(c=X,z(T)):xt(T)?(e.consume(T),X):j(T)}function he(T){return T===45||Ji(T)?(e.consume(T),he):T===47||T===62||qt(T)?ye(T):i(T)}function ye(T){return T===47?(e.consume(T),j):T===58||T===95||un(T)?(e.consume(T),U):$e(T)?(c=ye,z(T)):xt(T)?(e.consume(T),ye):j(T)}function U(T){return T===45||T===46||T===58||T===95||Ji(T)?(e.consume(T),U):se(T)}function se(T){return T===61?(e.consume(T),W):$e(T)?(c=se,z(T)):xt(T)?(e.consume(T),se):ye(T)}function W(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):$e(T)?(c=W,z(T)):xt(T)?(e.consume(T),W):(e.consume(T),Z)}function G(T){return T===a?(e.consume(T),a=void 0,I):T===null?i(T):$e(T)?(c=G,z(T)):(e.consume(T),G)}function Z(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?ye(T):(e.consume(T),Z)}function I(T){return T===47||T===62||qt(T)?ye(T):i(T)}function j(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function z(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),B}function B(T){return xt(T)?Ct(e,_e,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):_e(T)}function _e(T){return e.enter("htmlTextData"),c(T)}}const nm={name:"labelEnd",resolveAll:I5,resolveTo:H5,tokenize:U5},O5={tokenize:$5},z5={tokenize:F5},P5={tokenize:q5};function I5(e){let t=-1;const i=[];for(;++t=3&&(d===null||$e(d))?(e.exit("thematicBreak"),t(d)):i(d)}function p(d){return d===a?(e.consume(d),s++,p):(e.exit("thematicBreakSequence"),xt(d)?Ct(e,h,"whitespace")(d):h(d))}}const wn={continuation:{tokenize:eT},exit:iT,name:"list",tokenize:J5},Z5={partial:!0,tokenize:nT},Q5={partial:!0,tokenize:tT};function J5(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const y=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Cp(v)){if(s.containerState.type||(s.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(xu,i,d)(v):d(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Cp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),d(v)):i(v)}function d(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Lo,s.interrupt?i:x,e.attempt(Z5,b,_))}function x(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function _(v){return xt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function eT(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Lo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Ct(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!xt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Q5,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,Ct(e,e.attempt(wn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function tT(e,t,i){const s=this;return Ct(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function iT(e){e.exit(this.containerState.type)}function nT(e,t,i){const s=this;return Ct(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!xt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const yv={name:"setextUnderline",resolveTo:rT,tokenize:sT};function rT(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function sT(e,t,i){const s=this;let a;return o;function o(d){let x=s.events.length,_;for(;x--;)if(s.events[x][1].type!=="lineEnding"&&s.events[x][1].type!=="linePrefix"&&s.events[x][1].type!=="content"){_=s.events[x][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||_)?(e.enter("setextHeadingLine"),a=d,c(d)):i(d)}function c(d){return e.enter("setextHeadingLineSequence"),h(d)}function h(d){return d===a?(e.consume(d),h):(e.exit("setextHeadingLineSequence"),xt(d)?Ct(e,p,"lineSuffix")(d):p(d))}function p(d){return d===null||$e(d)?(e.exit("setextHeadingLine"),t(d)):i(d)}}const aT={tokenize:lT};function lT(e){const t=this,i=e.attempt(Lo,s,e.attempt(this.parser.constructs.flowInitial,a,Ct(e,e.attempt(this.parser.constructs.flow,a,e.attempt(d5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const oT={resolveAll:H0()},cT=I0("string"),uT=I0("text");function I0(e){return{resolveAll:H0(e==="text"?hT:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(x){return d(x)?o(x):h(x)}function h(x){if(x===null){i.consume(x);return}return i.enter("data"),i.consume(x),p}function p(x){return d(x)?(i.exit("data"),o(x)):(i.consume(x),p)}function d(x){if(x===null)return!0;const _=a[x];let b=-1;if(_)for(;++b<_.length;){const v=_[b];if(!v.previous||v.previous.call(s,s.previous))return!0}return!1}}}function H0(e){return t;function t(i,s){let a=-1,o;for(;++a<=i.length;)o===void 0?i[a]&&i[a][1].type==="data"&&(o=a,a++):(!i[a]||i[a][1].type!=="data")&&(a!==o+2&&(i[o][1].end=i[a-1][1].end,i.splice(o+2,a-o-2),a=o+2),o=void 0);return e?e(i,s):i}}function hT(e,t){let i=0;for(;++i<=e.length;)if((i===e.length||e[i][1].type==="lineEnding")&&e[i-1][1].type==="data"){const s=e[i-1][1],a=t.sliceStream(s);let o=a.length,c=-1,h=0,p;for(;o--;){const d=a[o];if(typeof d=="string"){for(c=d.length;d.charCodeAt(c-1)===32;)h++,c--;if(c)break;c=-1}else if(d===-2)p=!0,h++;else if(d!==-1){o++;break}}if(t._contentTypeTextTrailing&&i===e.length&&(h=0),h){const d={type:i===e.length||p||h<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?c:s.start._bufferIndex+c,_index:s.start._index+o,line:s.end.line,column:s.end.column-h,offset:s.end.offset-h},end:{...s.end}};s.end={...d.start},s.start.offset===s.end.offset?Object.assign(s,d):(e.splice(i,0,["enter",d,t],["exit",d,t]),i+=2)}i++}return e}const dT={42:wn,43:wn,45:wn,48:wn,49:wn,50:wn,51:wn,52:wn,53:wn,54:wn,55:wn,56:wn,57:wn,62:M0},fT={91:_5},pT={[-2]:mf,[-1]:mf,32:mf},mT={35:w5,42:xu,45:[yv,xu],60:N5,61:yv,95:xu,96:bv,126:bv},gT={38:B0,92:D0},_T={[-5]:gf,[-4]:gf,[-3]:gf,33:W5,38:B0,42:kp,60:[YN,B5],91:Y5,92:[y5,D0],93:nm,95:kp,96:a5},xT={null:[kp,oT]},bT={null:[42,95]},vT={null:[]},yT=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:bT,contentInitial:fT,disable:vT,document:dT,flow:mT,flowInitial:pT,insideSpan:xT,string:gT,text:_T},Symbol.toStringTag,{value:"Module"}));function ST(e,t,i){let s={_bufferIndex:-1,_index:0,line:i&&i.line||1,column:i&&i.column||1,offset:i&&i.offset||0};const a={},o=[];let c=[],h=[];const p={attempt:X($),check:X(M),consume:L,enter:O,exit:J,interrupt:X(M,{interrupt:!0})},d={code:null,containerState:{},defineSkip:E,events:[],now:y,parser:e,previous:null,sliceSerialize:b,sliceStream:v,write:_};let x=t.tokenize.call(d,p);return t.resolveAll&&o.push(t),d;function _(se){return c=tr(c,se),A(),c[c.length-1]!==null?[]:(he(t,0),d.events=Iu(o,d.events,d),d.events)}function b(se,W){return CT(v(se),W)}function v(se){return wT(c,se)}function y(){const{_bufferIndex:se,_index:W,line:G,column:Z,offset:I}=s;return{_bufferIndex:se,_index:W,line:G,column:Z,offset:I}}function E(se){a[se.line]=se.column,U()}function A(){let se;for(;s._index-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function CT(e,t){let i=-1;const s=[];let a;for(;++inew Set(pt).add($))}},ue.term.onData(tt=>{Ze.readyState===WebSocket.OPEN&&Ze.send(tt)}),ue.ws=Ze},[e]);w.useEffect(()=>{X.current=xe},[xe]);const T=w.useCallback(async($,ue)=>{if(!y.current||Ai.has($))return;const{resume:be=!1,autoConnect:De=!0}=ue??{},Ee=document.createElement("div");Ee.style.width="100%",Ee.style.height="100%",Ee.style.display="none",Ee.style.paddingLeft="10px",Ee.style.boxSizing="border-box",y.current.appendChild(Ee);const Be=new TE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:UE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),je=new RE,Ze=new OE;Be.loadAddon(je),Be.loadAddon(Ze),Be.open(Ee);const Ce={term:Be,fit:je,serialize:Ze,ws:null,container:Ee,observer:null,connected:!1},tt=new ResizeObserver(()=>{var Ge;const{width:pt}=Ee.getBoundingClientRect();if(!(pt<50))try{je.fit(),((Ge=Ce.ws)==null?void 0:Ge.readyState)===WebSocket.OPEN&&Ce.ws.send(JSON.stringify({type:"resize",cols:Be.cols,rows:Be.rows}))}catch{}});tt.observe(Ee),Ce.observer=tt,Ai.set($,Ce),E(pt=>[...pt,$]);try{const pt=await qE($);if(pt){const Ge=tv(pt);Be.write(Ge),Ge!==pt&&Za($,Ge).catch(()=>{})}}catch{}De?xe($,Ce,be):P(pt=>new Set(pt).add($)),setTimeout(()=>I(Ce),50)},[xe,I]),R=w.useCallback(async($,ue)=>{const be=Ai.get($);be&&(be.ws&&(be.ws.close(),be.ws=null),ue||(await N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),be.term.clear()),xe($,be,ue))},[xe]),Y=w.useCallback($=>{const ue=Ai.get($);if(ue){try{const be=ue.serialize.serialize();Za($,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),Ai.delete($),E(be=>be.filter(De=>De!==$)),P(be=>{const De=new Set(be);return De.delete($),De}),i(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),a==null||a($)}},[i,a]),C=w.useCallback($=>{var be;const ue=Ai.get($);ue&&(((be=ue.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&ue.ws.send(`exit +`),hf($).catch(()=>{}),ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),Ai.delete($),E(De=>De.filter(Ee=>Ee!==$)),P(De=>{const Ee=new Set(De);return Ee.delete($),Ee}),i(`/api/terminal/${encodeURIComponent($)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a($))},[i,a]),se=w.useCallback(async($,ue,be)=>{const De=Ai.get($);if(!De||Ai.has(ue)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:$,newName:ue,...be??{}})})).ok)return!1;Ai.delete($),Ai.set(ue,De);try{const Be=De.serialize.serialize();await hf($),await Za(ue,Be)}catch{}return E(Be=>Be.map(je=>je===$?ue:je)),P(Be=>{if(!Be.has($))return Be;const je=new Set(Be);return je.delete($),je.add(ue),je}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(ue)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),X.current(ue,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=se),()=>{h&&(h.current=null)}),[h,se]),w.useEffect(()=>{if(t){if(W){j(null);return}if(G){j(null);return}Ai.has(t)?j(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then($=>$.ok?$.json():null).then($=>{if(!Ai.has(t)){const ue=($==null?void 0:$.sessionId)&&!($!=null&&$.running);T(t,{autoConnect:!ue}),j(t)}}).catch(()=>{Ai.has(t)||(T(t),j(t))})}},[t,T,j,W,G]),w.useEffect(()=>{const $=setInterval(()=>{for(const[ue,be]of Ai)if(be.connected)try{const De=be.serialize.serialize();Za(ue,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval($)},[]),w.useEffect(()=>()=>{for(const[$,ue]of Ai){try{const be=ue.serialize.serialize();Za($,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{})}Ai.clear()},[]);const te=t?D.has(t):!1,oe=A.length===0;return f.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&f.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[A.map($=>f.jsxs("div",{onClick:()=>s==null?void 0:s($),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${$===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[f.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${D.has($)?"bg-amber-500":$===t?"bg-green-600":"bg-muted/50"}`}),f.jsx("span",{className:`truncate max-w-[120px] ${$.startsWith("_new_")?"italic":""}`,children:$.startsWith("_new_")?"Untitled":$}),f.jsx("button",{onClick:ue=>{ue.stopPropagation(),$.startsWith("_new_")?q($):Y($)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},$)),t!=null&&t.startsWith("_new_")?f.jsx("button",{onClick:()=>q(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?f.jsx("button",{onClick:()=>Z(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),f.jsxs("div",{className:"relative flex-1 min-h-0",children:[f.jsx("div",{ref:y,className:"h-full"}),oe&&!W&&!G&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),f.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),W&&f.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),f.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?f.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Su(_)?f.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[zp," Then reopen this story."]}):f.jsxs("div",{className:"space-y-1",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:iv}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(iv),ye(!0),setTimeout(()=>ye(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:he?"Copied!":"Copy"})]})]})]})}),G&&!W&&f.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),f.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),f.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),f.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:U,onClick:async()=>{if(!U){re(!0);try{await(v==null?void 0:v())}finally{re(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:U?"Setting…":"Set this story's provider to Codex"})]})}),J&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),f.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:()=>{const $=J;q(null),C($)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),L&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),f.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>Z(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:async()=>{const $=L;Z(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$})})).ok&&(Y($),o==null||o($))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),te&&t&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>R(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),f.jsx("button",{onClick:()=>R(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),f.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function GE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const YE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,KE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,VE={};function rv(e,t){return(VE.jsx?KE:YE).test(e)}const XE=/[ \t\n\f\r]/g;function ZE(e){return typeof e=="object"?e.type==="text"?sv(e.value):!1:sv(e)}function sv(e){return e.replace(XE,"")===""}class Bo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Bo.prototype.normal={};Bo.prototype.property={};Bo.prototype.space=void 0;function g0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Bo(i,s,t)}function vp(e){return e.toLowerCase()}class Nn{constructor(t,i){this.attribute=i,this.property=t}}Nn.prototype.attribute="";Nn.prototype.booleanish=!1;Nn.prototype.boolean=!1;Nn.prototype.commaOrSpaceSeparated=!1;Nn.prototype.commaSeparated=!1;Nn.prototype.defined=!1;Nn.prototype.mustUseProperty=!1;Nn.prototype.number=!1;Nn.prototype.overloadedBoolean=!1;Nn.prototype.property="";Nn.prototype.spaceSeparated=!1;Nn.prototype.space=void 0;let QE=0;const ot=ua(),Si=ua(),yp=ua(),ve=ua(),Wt=ua(),il=ua(),Un=ua();function ua(){return 2**++QE}const Sp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Si,commaOrSpaceSeparated:Un,commaSeparated:il,number:ve,overloadedBoolean:yp,spaceSeparated:Wt},Symbol.toStringTag,{value:"Module"})),df=Object.keys(Sp);class Vp extends Nn{constructor(t,i,s,a){let o=-1;if(super(t,i),av(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&nN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(lv,aN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!lv.test(o)){let c=o.replace(iN,sN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Vp}return new a(s,t)}function sN(e){return"-"+e.toLowerCase()}function aN(e){return e.charAt(1).toUpperCase()}const lN=g0([x0,JE,v0,y0,S0],"html"),Xp=g0([x0,eN,v0,y0,S0],"svg");function oN(e){return e.join(" ").trim()}var Qa={},ff,ov;function cN(){if(ov)return ff;ov=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` +`,d="/",_="*",x="",b="comment",v="declaration";function y(A,E){if(typeof A!="string")throw new TypeError("First argument must be a string");if(!A)return[];E=E||{};var D=1,P=1;function J(X){var I=X.match(t);I&&(D+=I.length);var j=X.lastIndexOf(p);P=~j?X.length-j:P+X.length}function q(){var X={line:D,column:P};return function(I){return I.position=new L(X),ye(),I}}function L(X){this.start=X,this.end={line:D,column:P},this.source=E.source}L.prototype.content=A;function Z(X){var I=new Error(E.source+":"+D+":"+P+": "+X);if(I.reason=X,I.filename=E.source,I.line=D,I.column=P,I.source=A,!E.silent)throw I}function he(X){var I=X.exec(A);if(I){var j=I[0];return J(j),A=A.slice(j.length),I}}function ye(){he(i)}function U(X){var I;for(X=X||[];I=re();)I!==!1&&X.push(I);return X}function re(){var X=q();if(!(d!=A.charAt(0)||_!=A.charAt(1))){for(var I=2;x!=A.charAt(I)&&(_!=A.charAt(I)||d!=A.charAt(I+1));)++I;if(I+=2,x===A.charAt(I-1))return Z("End of comment missing");var j=A.slice(2,I-2);return P+=2,J(j),A=A.slice(I),P+=2,X({type:b,comment:j})}}function W(){var X=q(),I=he(s);if(I){if(re(),!he(a))return Z("property missing ':'");var j=he(o),O=X({type:v,property:N(I[0].replace(e,x)),value:j?N(j[0].replace(e,x)):x});return he(c),O}}function G(){var X=[];U(X);for(var I;I=W();)I!==!1&&(X.push(I),U(X));return X}return ye(),G()}function N(A){return A?A.replace(h,x):x}return ff=y,ff}var cv;function uN(){if(cv)return Qa;cv=1;var e=Qa&&Qa.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.default=i;const t=e(cN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:d,value:_}=p;h?a(d,_,p):_&&(o=o||{},o[d]=_)}),o}return Qa}var co={},uv;function hN(){if(uv)return co;uv=1,Object.defineProperty(co,"__esModule",{value:!0}),co.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(d){return!d||i.test(d)||e.test(d)},c=function(d,_){return _.toUpperCase()},h=function(d,_){return"".concat(_,"-")},p=function(d,_){return _===void 0&&(_={}),o(d)?d:(d=d.toLowerCase(),_.reactCompat?d=d.replace(a,h):d=d.replace(s,h),d.replace(t,c))};return co.camelCase=p,co}var uo,hv;function dN(){if(hv)return uo;hv=1;var e=uo&&uo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(uN()),i=hN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,uo=s,uo}var fN=dN();const pN=Du(fN),w0=C0("end"),Zp=C0("start");function C0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function k0(e){const t=Zp(e),i=w0(e);if(t&&i)return{start:t,end:i}}function vo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?dv(e.position):"start"in e||"end"in e?dv(e):"line"in e||"column"in e?wp(e):""}function wp(e){return fv(e&&e.line)+":"+fv(e&&e.column)}function dv(e){return wp(e&&e.start)+"-"+wp(e&&e.end)}function fv(e){return e&&typeof e=="number"?e:1}class rn extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=vo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}rn.prototype.file="";rn.prototype.name="";rn.prototype.reason="";rn.prototype.message="";rn.prototype.stack="";rn.prototype.column=void 0;rn.prototype.line=void 0;rn.prototype.ancestors=void 0;rn.prototype.cause=void 0;rn.prototype.fatal=void 0;rn.prototype.place=void 0;rn.prototype.ruleId=void 0;rn.prototype.source=void 0;const Qp={}.hasOwnProperty,mN=new Map,gN=/[A-Z]/g,xN=new Set(["table","tbody","thead","tfoot","tr"]),_N=new Set(["td","th"]),E0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function bN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=NN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=EN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Xp:lN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=N0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function N0(e,t,i){if(t.type==="element")return vN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return yN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return wN(e,t,i);if(t.type==="mdxjsEsm")return SN(e,t);if(t.type==="root")return CN(e,t,i);if(t.type==="text")return kN(e,t)}function vN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=j0(e,t.tagName,!1),c=TN(e,t);let h=em(e,t);return xN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!ZE(p):!0})),T0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function yN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Eo(e,t.position)}function SN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Eo(e,t.position)}function wN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:j0(e,t.name,!0),c=jN(e,t),h=em(e,t);return T0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function CN(e,t,i){const s={};return Jp(s,em(e,t)),e.create(t,e.Fragment,s,i)}function kN(e,t){return t.value}function T0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function Jp(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function EN(e,t,i){return s;function s(a,o,c,h){const d=Array.isArray(c.children)?i:t;return h?d(o,c,h):d(o,c)}}function NN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=Zp(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function TN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&Qp.call(t.properties,a)){const o=AN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&_N.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function jN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Eo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Eo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function em(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:mN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?($n(e,e.length,0,t),e):t}const gv={}.hasOwnProperty;function R0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function pr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const dn=Bs(/[A-Za-z]/),nn=Bs(/[\dA-Za-z]/),IN=Bs(/[#-'*+\--9=?A-Z^-~]/);function ju(e){return e!==null&&(e<32||e===127)}const Cp=Bs(/\d/),HN=Bs(/[\dA-Fa-f]/),UN=Bs(/[!-/:-@[-`{-~]/);function $e(e){return e!==null&&e<-2}function Ft(e){return e!==null&&(e<0||e===32)}function xt(e){return e===-2||e===-1||e===32}const Pu=Bs(new RegExp("\\p{P}|\\p{S}","u")),oa=Bs(/\s/);function Bs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function hl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function Ct(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return xt(p)?(e.enter(i),h(p)):t(p)}function h(p){return xt(p)&&o++c))return;const Z=t.events.length;let he=Z,ye,U;for(;he--;)if(t.events[he][0]==="exit"&&t.events[he][1].type==="chunkFlow"){if(ye){U=t.events[he][1].end;break}ye=!0}for(E(s),L=Z;LP;){const q=i[J];t.containerState=q[1],q[0].exit.call(t,e)}i.length=P}function D(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function GN(e,t,i){return Ct(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function al(e){if(e===null||Ft(e)||oa(e))return 1;if(Pu(e))return 2}function Iu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};_v(x,-p),_v(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},d=[],e[s][1].end.offset-e[s][1].start.offset&&(d=rr(d,[["enter",e[s][1],t],["exit",e[s][1],t]])),d=rr(d,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),d=rr(d,Iu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),d=rr(d,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,d=rr(d,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,$n(e,s-1,i-s+3,d),i=s+d.length-_-2;break}}for(i=-1;++i0&&xt(L)?Ct(e,D,"linePrefix",o+1)(L):D(L)}function D(L){return L===null||$e(L)?e.check(bv,N,J)(L):(e.enter("codeFlowValue"),P(L))}function P(L){return L===null||$e(L)?(e.exit("codeFlowValue"),D(L)):(e.consume(L),P)}function J(L){return e.exit("codeFenced"),t(L)}function q(L,Z,he){let ye=0;return U;function U(I){return L.enter("lineEnding"),L.consume(I),L.exit("lineEnding"),re}function re(I){return L.enter("codeFencedFence"),xt(I)?Ct(L,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(L.enter("codeFencedFenceSequence"),G(I)):he(I)}function G(I){return I===h?(ye++,L.consume(I),G):ye>=c?(L.exit("codeFencedFenceSequence"),xt(I)?Ct(L,X,"whitespace")(I):X(I)):he(I)}function X(I){return I===null||$e(I)?(L.exit("codeFencedFence"),Z(I)):he(I)}}}function r5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const mf={name:"codeIndented",tokenize:a5},s5={partial:!0,tokenize:l5};function a5(e,t,i){const s=this;return a;function a(d){return e.enter("codeIndented"),Ct(e,o,"linePrefix",5)(d)}function o(d){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(d):i(d)}function c(d){return d===null?p(d):$e(d)?e.attempt(s5,c,p)(d):(e.enter("codeFlowValue"),h(d))}function h(d){return d===null||$e(d)?(e.exit("codeFlowValue"),c(d)):(e.consume(d),h)}function p(d){return e.exit("codeIndented"),t(d)}}function l5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):$e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):Ct(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):$e(c)?a(c):i(c)}}const o5={name:"codeText",previous:u5,resolve:c5,tokenize:h5};function c5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&ho(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ho(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function z0(e,t,i,s,a,o,c,h,p){const d=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||ju(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),N(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||$e(E)?i(E):(e.consume(E),E===92?y:v)}function y(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||Ft(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):$e(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||$e(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!xt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function I0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),d(b))}function d(b){return b===c?(e.exit(o),p(c)):b===null?i(b):$e(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),Ct(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||$e(b)?(e.exit("chunkString"),d(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function yo(e,t){let i;return s;function s(a){return $e(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?Ct(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const b5={name:"definition",tokenize:y5},v5={partial:!0,tokenize:S5};function y5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return P0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=pr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return Ft(v)?yo(e,d)(v):d(v)}function d(v){return z0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(v5,x,x)(v)}function x(v){return xt(v)?Ct(e,b,"whitespace")(v):b(v)}function b(v){return v===null||$e(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function S5(e,t,i){return s;function s(h){return Ft(h)?yo(e,a)(h):i(h)}function a(h){return I0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?Ct(e,c,"whitespace")(h):c(h)}function c(h){return h===null||$e(h)?t(h):i(h)}}const w5={name:"hardBreakEscape",tokenize:C5};function C5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return $e(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const k5={name:"headingAtx",resolve:E5,tokenize:N5};function E5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},$n(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function N5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||Ft(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||$e(_)?(e.exit("atxHeading"),t(_)):xt(_)?Ct(e,h,"whitespace")(_):(e.enter("atxHeadingText"),d(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function d(_){return _===null||_===35||Ft(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),d)}}const T5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],yv=["pre","script","style","textarea"],j5={concrete:!0,name:"htmlFlow",resolveTo:M5,tokenize:D5},A5={partial:!0,tokenize:L5},R5={partial:!0,tokenize:B5};function M5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function D5(e,t,i){const s=this;let a,o,c,h,p;return d;function d(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,N):C===63?(e.consume(C),a=3,s.interrupt?t:T):dn(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,y):dn(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function y(C){const se="CDATA[";return C===se.charCodeAt(h++)?(e.consume(C),h===se.length?s.interrupt?t:W:y):i(C)}function N(C){return dn(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function A(C){if(C===null||C===47||C===62||Ft(C)){const se=C===47,te=c.toLowerCase();return!se&&!o&&yv.includes(te)?(a=1,s.interrupt?t(C):W(C)):T5.includes(c.toLowerCase())?(a=6,se?(e.consume(C),E):s.interrupt?t(C):W(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?D(C):P(C))}return C===45||nn(C)?(e.consume(C),c+=String.fromCharCode(C),A):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:W):i(C)}function D(C){return xt(C)?(e.consume(C),D):U(C)}function P(C){return C===47?(e.consume(C),U):C===58||C===95||dn(C)?(e.consume(C),J):xt(C)?(e.consume(C),P):U(C)}function J(C){return C===45||C===46||C===58||C===95||nn(C)?(e.consume(C),J):q(C)}function q(C){return C===61?(e.consume(C),L):xt(C)?(e.consume(C),q):P(C)}function L(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,Z):xt(C)?(e.consume(C),L):he(C)}function Z(C){return C===p?(e.consume(C),p=null,ye):C===null||$e(C)?i(C):(e.consume(C),Z)}function he(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Ft(C)?q(C):(e.consume(C),he)}function ye(C){return C===47||C===62||xt(C)?P(C):i(C)}function U(C){return C===62?(e.consume(C),re):i(C)}function re(C){return C===null||$e(C)?W(C):xt(C)?(e.consume(C),re):i(C)}function W(C){return C===45&&a===2?(e.consume(C),j):C===60&&a===1?(e.consume(C),O):C===62&&a===4?(e.consume(C),R):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),xe):$e(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(A5,Y,G)(C)):C===null||$e(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),W)}function G(C){return e.check(R5,X,Y)(C)}function X(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),I}function I(C){return C===null||$e(C)?G(C):(e.enter("htmlFlowData"),W(C))}function j(C){return C===45?(e.consume(C),T):W(C)}function O(C){return C===47?(e.consume(C),c="",B):W(C)}function B(C){if(C===62){const se=c.toLowerCase();return yv.includes(se)?(e.consume(C),R):W(C)}return dn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),B):W(C)}function xe(C){return C===93?(e.consume(C),T):W(C)}function T(C){return C===62?(e.consume(C),R):C===45&&a===2?(e.consume(C),T):W(C)}function R(C){return C===null||$e(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),R)}function Y(C){return e.exit("htmlFlow"),t(C)}}function B5(e,t,i){const s=this;return a;function a(c){return $e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function L5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Lo,t,i)}}const O5={name:"htmlText",tokenize:z5};function z5(e,t,i){const s=this;let a,o,c;return h;function h(T){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(T),p}function p(T){return T===33?(e.consume(T),d):T===47?(e.consume(T),q):T===63?(e.consume(T),P):dn(T)?(e.consume(T),he):i(T)}function d(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,y):dn(T)?(e.consume(T),D):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):$e(T)?(c=x,O(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?j(T):T===45?b(T):x(T)}function y(T){const R="CDATA[";return T===R.charCodeAt(o++)?(e.consume(T),o===R.length?N:y):i(T)}function N(T){return T===null?i(T):T===93?(e.consume(T),A):$e(T)?(c=N,O(T)):(e.consume(T),N)}function A(T){return T===93?(e.consume(T),E):N(T)}function E(T){return T===62?j(T):T===93?(e.consume(T),E):N(T)}function D(T){return T===null||T===62?j(T):$e(T)?(c=D,O(T)):(e.consume(T),D)}function P(T){return T===null?i(T):T===63?(e.consume(T),J):$e(T)?(c=P,O(T)):(e.consume(T),P)}function J(T){return T===62?j(T):P(T)}function q(T){return dn(T)?(e.consume(T),L):i(T)}function L(T){return T===45||nn(T)?(e.consume(T),L):Z(T)}function Z(T){return $e(T)?(c=Z,O(T)):xt(T)?(e.consume(T),Z):j(T)}function he(T){return T===45||nn(T)?(e.consume(T),he):T===47||T===62||Ft(T)?ye(T):i(T)}function ye(T){return T===47?(e.consume(T),j):T===58||T===95||dn(T)?(e.consume(T),U):$e(T)?(c=ye,O(T)):xt(T)?(e.consume(T),ye):j(T)}function U(T){return T===45||T===46||T===58||T===95||nn(T)?(e.consume(T),U):re(T)}function re(T){return T===61?(e.consume(T),W):$e(T)?(c=re,O(T)):xt(T)?(e.consume(T),re):ye(T)}function W(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):$e(T)?(c=W,O(T)):xt(T)?(e.consume(T),W):(e.consume(T),X)}function G(T){return T===a?(e.consume(T),a=void 0,I):T===null?i(T):$e(T)?(c=G,O(T)):(e.consume(T),G)}function X(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||Ft(T)?ye(T):(e.consume(T),X)}function I(T){return T===47||T===62||Ft(T)?ye(T):i(T)}function j(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function O(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),B}function B(T){return xt(T)?Ct(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):xe(T)}function xe(T){return e.enter("htmlTextData"),c(T)}}const nm={name:"labelEnd",resolveAll:U5,resolveTo:$5,tokenize:F5},P5={tokenize:q5},I5={tokenize:W5},H5={tokenize:G5};function U5(e){let t=-1;const i=[];for(;++t=3&&(d===null||$e(d))?(e.exit("thematicBreak"),t(d)):i(d)}function p(d){return d===a?(e.consume(d),s++,p):(e.exit("thematicBreakSequence"),xt(d)?Ct(e,h,"whitespace")(d):h(d))}}const En={continuation:{tokenize:iT},exit:rT,name:"list",tokenize:tT},J5={partial:!0,tokenize:sT},eT={partial:!0,tokenize:nT};function tT(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const y=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Cp(v)){if(s.containerState.type||(s.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(_u,i,d)(v):d(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Cp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),d(v)):i(v)}function d(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Lo,s.interrupt?i:_,e.attempt(J5,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return xt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function iT(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Lo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Ct(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!xt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(eT,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,Ct(e,e.attempt(En,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function nT(e,t,i){const s=this;return Ct(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function rT(e){e.exit(this.containerState.type)}function sT(e,t,i){const s=this;return Ct(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!xt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const Sv={name:"setextUnderline",resolveTo:aT,tokenize:lT};function aT(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function lT(e,t,i){const s=this;let a;return o;function o(d){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=d,c(d)):i(d)}function c(d){return e.enter("setextHeadingLineSequence"),h(d)}function h(d){return d===a?(e.consume(d),h):(e.exit("setextHeadingLineSequence"),xt(d)?Ct(e,p,"lineSuffix")(d):p(d))}function p(d){return d===null||$e(d)?(e.exit("setextHeadingLine"),t(d)):i(d)}}const oT={tokenize:cT};function cT(e){const t=this,i=e.attempt(Lo,s,e.attempt(this.parser.constructs.flowInitial,a,Ct(e,e.attempt(this.parser.constructs.flow,a,e.attempt(p5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const uT={resolveAll:U0()},hT=H0("string"),dT=H0("text");function H0(e){return{resolveAll:U0(e==="text"?fT:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(_){return d(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return d(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function d(_){if(_===null)return!0;const x=a[_];let b=-1;if(x)for(;++b-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function ET(e,t){let i=-1;const s=[];let a;for(;++i0){const H=Pe.tokenStack[Pe.tokenStack.length-1];(H[1]||wv).call(Pe,void 0,H[0])}for(xe.position={start:Ts(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:Ts(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Qe=-1;++Qe0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function PT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function IT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function HT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=dl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const d={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,d),e.applyData(t,d)}function UT(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function $T(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function F0(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function FT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return F0(e,t);const a={src:dl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function qT(e,t){const i={src:dl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function WT(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function GT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return F0(e,t);const a={href:dl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function YT(e,t){const i={href:dl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function KT(e,t,i){const s=e.all(t),a=i?VT(i):q0(t),o={},c=[];if(typeof t.checked=="boolean"){const x=s[0];let _;x&&x.type==="element"&&x.tagName==="p"?_=x:(_={type:"element",tagName:"p",properties:{},children:[]},s.unshift(_)),_.children.length>0&&_.children.unshift({type:"text",value:" "}),_.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h1}function XT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=Zp(t.children[1]),p=S0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function tj(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const d=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Ev(t.slice(a),a>0,!1)),o.join("")}function Ev(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Cv||o===kv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Cv||o===kv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function rj(e,t){const i={type:"text",value:nj(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function sj(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const aj={blockquote:LT,break:OT,code:zT,delete:PT,emphasis:IT,footnoteReference:HT,heading:UT,html:$T,imageReference:FT,image:qT,inlineCode:WT,linkReference:GT,link:YT,listItem:KT,list:XT,paragraph:ZT,root:QT,strong:JT,table:ej,tableCell:ij,tableRow:tj,text:rj,thematicBreak:sj,toml:eu,yaml:eu,definition:eu,footnoteDefinition:eu};function eu(){}const W0=-1,Hu=0,So=1,Au=2,rm=3,sm=4,am=5,lm=6,G0=7,Y0=8,Nv=typeof self=="object"?self:globalThis,lj=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Hu:case W0:return i(c,a);case So:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Au:{const h=i({},a);for(const[p,d]of c)h[s(p)]=s(d);return h}case rm:return i(new Date(c),a);case sm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case am:{const h=i(new Map,a);for(const[p,d]of c)h.set(s(p),s(d));return h}case lm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case G0:{const{name:h,message:p}=c;return i(new Nv[h](p),a)}case Y0:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Nv[o](c),a)};return s},Tv=e=>lj(new Map,e)(0),el="",{toString:oj}={},{keys:cj}=Object,fo=e=>{const t=typeof e;if(t!=="object"||!e)return[Hu,t];const i=oj.call(e).slice(8,-1);switch(i){case"Array":return[So,el];case"Object":return[Au,el];case"Date":return[rm,el];case"RegExp":return[sm,el];case"Map":return[am,el];case"Set":return[lm,el];case"DataView":return[So,i]}return i.includes("Array")?[So,i]:i.includes("Error")?[G0,i]:[Au,i]},tu=([e,t])=>e===Hu&&(t==="function"||t==="symbol"),uj=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=fo(c);switch(h){case Hu:{let x=c;switch(p){case"bigint":h=Y0,x=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);x=null;break;case"undefined":return a([W0],c)}return a([h,x],c)}case So:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const x=[],_=a([h,x],c);for(const b of c)x.push(o(b));return _}case Au:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const x=[],_=a([h,x],c);for(const b of cj(c))(e||!tu(fo(c[b])))&&x.push([o(b),o(c[b])]);return _}case rm:return a([h,c.toISOString()],c);case sm:{const{source:x,flags:_}=c;return a([h,{source:x,flags:_}],c)}case am:{const x=[],_=a([h,x],c);for(const[b,v]of c)(e||!(tu(fo(b))||tu(fo(v))))&&x.push([o(b),o(v)]);return _}case lm:{const x=[],_=a([h,x],c);for(const b of c)(e||!tu(fo(b)))&&x.push(o(b));return _}}const{message:d}=c;return a([h,{name:p,message:d}],c)};return o},jv=(e,{json:t,lossy:i}={})=>{const s=[];return uj(!(t||i),!!t,new Map,s)(e),s},No=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Tv(jv(e,t)):structuredClone(e):(e,t)=>Tv(jv(e,t));function hj(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function dj(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function fj(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||hj,s=e.options.footnoteBackLabel||dj,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&y.push({type:"text",value:" "});let L=typeof i=="string"?i:i(p,v);typeof L=="string"&&(L={type:"text",value:L}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(L)?L:[L]})}const A=x[x.length-1];if(A&&A.type==="element"&&A.tagName==="p"){const L=A.children[A.children.length-1];L&&L.type==="text"?L.value+=" ":A.children.push({type:"text",value:" "}),A.children.push(...y)}else x.push(...y);const N={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(x,!0)};e.patch(d,N),h.push(N)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...No(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`;break}case-2:{c=t?" ":" ";break}case-1:{if(!t&&a)continue;c=" ";break}default:c=String.fromCharCode(o)}a=o===-2,s.push(c)}return s.join("")}function NT(e){const s={constructs:R0([wT,...(e||{}).extensions||[]]),content:a($N),defined:[],document:a(qN),flow:a(oT),lazy:{},string:a(hT),text:a(dT)};return s;function a(o){return c;function c(h){return CT(s,o,h)}}}function TT(e){for(;!O0(e););return e}const wv=/[\0\t\n\r]/g;function jT(){let e=1,t="",i=!0,s;return a;function a(o,c,h){const p=[];let d,_,x,b,v;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(c||void 0).decode(o)),x=0,t="",i&&(o.charCodeAt(0)===65279&&x++,i=void 0);x0){const H=Pe.tokenStack[Pe.tokenStack.length-1];(H[1]||Cv).call(Pe,void 0,H[0])}for(_e.position={start:Ts(ne.length>0?ne[0][1].start:{line:1,column:1,offset:0}),end:Ts(ne.length>0?ne[ne.length-2][1].end:{line:1,column:1,offset:0})},Qe=-1;++Qe0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function HT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function UT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function $T(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=hl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const d={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,d),e.applyData(t,d)}function FT(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function qT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function q0(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function WT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return q0(e,t);const a={src:hl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function GT(e,t){const i={src:hl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function YT(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function KT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return q0(e,t);const a={href:hl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function VT(e,t){const i={href:hl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function XT(e,t,i){const s=e.all(t),a=i?ZT(i):W0(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h1}function QT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=Zp(t.children[1]),p=w0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function nj(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const d=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Nv(t.slice(a),a>0,!1)),o.join("")}function Nv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===kv||o===Ev;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===kv||o===Ev;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function aj(e,t){const i={type:"text",value:sj(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function lj(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const oj={blockquote:zT,break:PT,code:IT,delete:HT,emphasis:UT,footnoteReference:$T,heading:FT,html:qT,imageReference:WT,image:GT,inlineCode:YT,linkReference:KT,link:VT,listItem:XT,list:QT,paragraph:JT,root:ej,strong:tj,table:ij,tableCell:rj,tableRow:nj,text:aj,thematicBreak:lj,toml:eu,yaml:eu,definition:eu,footnoteDefinition:eu};function eu(){}const G0=-1,Hu=0,So=1,Au=2,rm=3,sm=4,am=5,lm=6,Y0=7,K0=8,Tv=typeof self=="object"?self:globalThis,cj=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Hu:case G0:return i(c,a);case So:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Au:{const h=i({},a);for(const[p,d]of c)h[s(p)]=s(d);return h}case rm:return i(new Date(c),a);case sm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case am:{const h=i(new Map,a);for(const[p,d]of c)h.set(s(p),s(d));return h}case lm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case Y0:{const{name:h,message:p}=c;return i(new Tv[h](p),a)}case K0:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Tv[o](c),a)};return s},jv=e=>cj(new Map,e)(0),Ja="",{toString:uj}={},{keys:hj}=Object,fo=e=>{const t=typeof e;if(t!=="object"||!e)return[Hu,t];const i=uj.call(e).slice(8,-1);switch(i){case"Array":return[So,Ja];case"Object":return[Au,Ja];case"Date":return[rm,Ja];case"RegExp":return[sm,Ja];case"Map":return[am,Ja];case"Set":return[lm,Ja];case"DataView":return[So,i]}return i.includes("Array")?[So,i]:i.includes("Error")?[Y0,i]:[Au,i]},tu=([e,t])=>e===Hu&&(t==="function"||t==="symbol"),dj=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=fo(c);switch(h){case Hu:{let _=c;switch(p){case"bigint":h=K0,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([G0],c)}return a([h,_],c)}case So:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Au:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of hj(c))(e||!tu(fo(c[b])))&&_.push([o(b),o(c[b])]);return x}case rm:return a([h,c.toISOString()],c);case sm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case am:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(tu(fo(b))||tu(fo(v))))&&_.push([o(b),o(v)]);return x}case lm:{const _=[],x=a([h,_],c);for(const b of c)(e||!tu(fo(b)))&&_.push(o(b));return x}}const{message:d}=c;return a([h,{name:p,message:d}],c)};return o},Av=(e,{json:t,lossy:i}={})=>{const s=[];return dj(!(t||i),!!t,new Map,s)(e),s},No=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?jv(Av(e,t)):structuredClone(e):(e,t)=>jv(Av(e,t));function fj(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function pj(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function mj(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||fj,s=e.options.footnoteBackLabel||pj,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&y.push({type:"text",value:" "});let D=typeof i=="string"?i:i(p,v);typeof D=="string"&&(D={type:"text",value:D}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(D)?D:[D]})}const A=_[_.length-1];if(A&&A.type==="element"&&A.tagName==="p"){const D=A.children[A.children.length-1];D&&D.type==="text"?D.value+=" ":A.children.push({type:"text",value:" "}),A.children.push(...y)}else _.push(...y);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(d,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...No(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` -`}]}}const Uu=(function(e){if(e==null)return _j;if(typeof e=="function")return $u(e);if(typeof e=="object")return Array.isArray(e)?pj(e):mj(e);if(typeof e=="string")return gj(e);throw new Error("Expected function, string, or object as test")});function pj(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=K0,y,E,A;if((!t||o(p,d,x[x.length-1]||void 0))&&(v=yj(i(p,x)),v[0]===Ep))return v;if("children"in p&&p.children){const N=p;if(N.children&&v[0]!==vj)for(E=(s?N.children.length:-1)+c,A=x.concat(N);E>-1&&E":""))+")"})}return b;function b(){let v=V0,y,N,A;if((!t||o(p,d,_[_.length-1]||void 0))&&(v=wj(i(p,_)),v[0]===Ep))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==Sj)for(N=(s?E.children.length:-1)+c,A=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` -`}),i}function Av(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Rv(e,t){const i=wj(e,t),s=i.one(e,void 0),a=fj(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function Tj(e,t){return e&&"run"in e?async function(i,s){const a=Rv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Rv(i,{file:s,...e||t})}}function Mv(e){if(e)throw e}var _f,Dv;function jj(){if(Dv)return _f;Dv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(d){return typeof Array.isArray=="function"?Array.isArray(d):t.call(d)==="[object Array]"},o=function(d){if(!d||t.call(d)!=="[object Object]")return!1;var x=e.call(d,"constructor"),_=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!x&&!_)return!1;var b;for(b in d);return typeof b>"u"||e.call(d,b)},c=function(d,x){i&&x.name==="__proto__"?i(d,x.name,{enumerable:!0,configurable:!0,value:x.newValue,writable:!0}):d[x.name]=x.newValue},h=function(d,x){if(x==="__proto__")if(e.call(d,x)){if(s)return s(d,x).value}else return;return d[x]};return _f=function p(){var d,x,_,b,v,y,E=arguments[0],A=1,N=arguments.length,L=!1;for(typeof E=="boolean"&&(L=E,E=arguments[1]||{},A=2),(E==null||typeof E!="object"&&typeof E!="function")&&(E={});Ac.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(d){const x=d;if(h&&i)throw x;return a(x)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const Sr={basename:Dj,dirname:Bj,extname:Lj,join:Oj,sep:"/"};function Dj(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Oo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function Bj(e){if(Oo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Lj(e){Oo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function Oj(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function Pj(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Oo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Ij={cwd:Hj};function Hj(){return"/"}function jp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Uj(e){if(typeof e=="string")e=new URL(e);else if(!jp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return $j(e)}function $j(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...y]=x;const E=s[b][1];Tp(E)&&Tp(v)&&(v=xf(!0,E,v)),s[b]=[d,v,...y]}}}}const Gj=new cm().freeze();function Sf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Cf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Lv(e){if(!Tp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ov(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function iu(e){return Yj(e)?e:new X0(e)}function Yj(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Kj(e){return typeof e=="string"||Vj(e)}function Vj(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Xj="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",zv=[],Pv={allowDangerousHtml:!0},Zj=/^(https?|ircs?|mailto|xmpp)$/i,Qj=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Z0(e){const t=Jj(e),i=eA(e);return tA(t.runSync(t.parse(i),i),e)}function Jj(e){const t=e.rehypePlugins||zv,i=e.remarkPlugins||zv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Pv}:Pv;return Gj().use(BT).use(i).use(Tj,s).use(t)}function eA(e){const t=e.children||"",i=new X0;return typeof t=="string"&&(i.value=t),i}function tA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||iA;for(const x of Qj)Object.hasOwn(t,x.from)&&(""+x.from+(x.to?"use `"+x.to+"` instead":"remove it")+Xj+x.id,void 0);return om(e,d),_N(e,{Fragment:f.Fragment,components:a,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function d(x,_,b){if(x.type==="raw"&&b&&typeof _=="number")return c?b.children.splice(_,1):b.children[_]={type:"text",value:x.value},_;if(x.type==="element"){let v;for(v in pf)if(Object.hasOwn(pf,v)&&Object.hasOwn(x.properties,v)){const y=x.properties[v],E=pf[v];(E===null||E.includes(x.tagName))&&(x.properties[v]=p(String(y||""),v,x))}}if(x.type==="element"){let v=i?!i.includes(x.tagName):o?o.includes(x.tagName):!1;if(!v&&s&&typeof _=="number"&&(v=!s(x,_,b)),v&&b&&typeof _=="number")return h&&x.children?b.children.splice(_,1,...x.children):b.children.splice(_,1),_}}}function iA(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||Zj.test(e.slice(0,t))?e:""}function nA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Q0(e,t,i){const a=Uu((i||{}).ignore||[]),o=rA(t);let c=-1;for(;++c0?{type:"text",value:M}:void 0),M===!1?b.lastIndex=J+1:(y!==J&&L.push({type:"text",value:d.value.slice(y,J)}),Array.isArray(M)?L.push(...M):M&&L.push(M),y=J+O[0].length,N=!0),!b.global)break;O=b.exec(d.value)}return N?(y?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Iv(e,"(");let o=Iv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function eS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||oa(i)||Pu(i))&&(!t||i!==47)}tS.peek=jA;function yA(){this.buffer()}function SA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function wA(){this.buffer()}function CA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function kA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=dr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function EA(e){this.exit(e)}function NA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=dr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function TA(e){this.exit(e)}function jA(){return"["}function tS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function AA(){return{enter:{gfmFootnoteCallString:yA,gfmFootnoteCall:SA,gfmFootnoteDefinitionLabelString:wA,gfmFootnoteDefinition:CA},exit:{gfmFootnoteCallString:kA,gfmFootnoteCall:EA,gfmFootnoteDefinitionLabelString:NA,gfmFootnoteDefinition:TA}}}function RA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:tS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const d=o.enter("footnoteDefinition"),x=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),x(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` -`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?iS:MA))),d(),p}}function MA(e,t,i){return t===0?e:iS(e,t,i)}function iS(e,t,i){return(i?"":" ")+e}const DA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];nS.peek=PA;function BA(){return{canContainEols:["delete"],enter:{strikethrough:OA},exit:{strikethrough:zA}}}function LA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:DA}],handlers:{delete:nS}}}function OA(e){this.enter({type:"delete",children:[]},e)}function zA(e){this.exit(e)}function nS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function PA(){return"~"}function IA(e){return e.length}function HA(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||IA,o=[],c=[],h=[],p=[];let d=0,x=-1;for(;++xd&&(d=e[x].length);++Np[N])&&(p[N]=O)}E.push(L)}c[x]=E,h[x]=A}let _=-1;if(typeof s=="object"&&"length"in s)for(;++_p[_]&&(p[_]=L),v[_]=L),b[_]=O}c.splice(1,0,b),h.splice(1,0,v),x=-1;const y=[];for(;++x "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),FA);return a(),c}function FA(e,t,i){return">"+(i?"":" ")+e}function qA(e,t){return Uv(e,t.inConstruct,!0)&&!Uv(e,t.notInConstruct,!1)}function Uv(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function GA(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function YA(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function KA(e,t,i,s){const a=YA(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(GA(e,i)){const _=i.enter("codeIndented"),b=i.indentLines(o,VA);return _(),b}const h=i.createTracker(s),p=a.repeat(Math.max(WA(o,a)+1,3)),d=i.enter("codeFenced");let x=h.move(p);if(e.lang){const _=i.enter(`codeFencedLang${c}`);x+=h.move(i.safe(e.lang,{before:x,after:" ",encode:["`"],...h.current()})),_()}if(e.lang&&e.meta){const _=i.enter(`codeFencedMeta${c}`);x+=h.move(" "),x+=h.move(i.safe(e.meta,{before:x,after:` -`,encode:["`"],...h.current()})),_()}return x+=h.move(` -`),o&&(x+=h.move(o+` -`)),x+=h.move(p),d(),x}function VA(e,t,i){return(i?"":" ")+e}function um(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function XA(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("[");return d+=p.move(i.safe(i.associationId(e),{before:d,after:"]",...p.current()})),d+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),c(),d}function ZA(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function To(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ru(e,t,i){const s=ll(e),a=ll(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}rS.peek=QA;function rS(e,t,i,s){const a=ZA(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),x=Ru(s.before.charCodeAt(s.before.length-1),d,a);x.inside&&(p=To(d)+p.slice(1));const _=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),_,a);b.inside&&(p=p.slice(0,-1)+To(_));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:x.outside},h+p+v}function QA(e,t,i){return i.options.emphasis||"*"}function JA(e,t){let i=!1;return om(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ep}),!!((!e.depth||e.depth<3)&&tm(e)&&(t.options.setext||i))}function eR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(JA(e,i)){const x=i.enter("headingSetext"),_=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`}),i}function Rv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Mv(e,t){const i=kj(e,t),s=i.one(e,void 0),a=mj(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function Aj(e,t){return e&&"run"in e?async function(i,s){const a=Mv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Mv(i,{file:s,...e||t})}}function Dv(e){if(e)throw e}var xf,Bv;function Rj(){if(Bv)return xf;Bv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(d){return typeof Array.isArray=="function"?Array.isArray(d):t.call(d)==="[object Array]"},o=function(d){if(!d||t.call(d)!=="[object Object]")return!1;var _=e.call(d,"constructor"),x=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!_&&!x)return!1;var b;for(b in d);return typeof b>"u"||e.call(d,b)},c=function(d,_){i&&_.name==="__proto__"?i(d,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):d[_.name]=_.newValue},h=function(d,_){if(_==="__proto__")if(e.call(d,_)){if(s)return s(d,_).value}else return;return d[_]};return xf=function p(){var d,_,x,b,v,y,N=arguments[0],A=1,E=arguments.length,D=!1;for(typeof N=="boolean"&&(D=N,N=arguments[1]||{},A=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Ac.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(d){const _=d;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const wr={basename:Lj,dirname:Oj,extname:zj,join:Pj,sep:"/"};function Lj(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Oo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function Oj(e){if(Oo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function zj(e){Oo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function Pj(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function Hj(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Oo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Uj={cwd:$j};function $j(){return"/"}function jp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Fj(e){if(typeof e=="string")e=new URL(e);else if(!jp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return qj(e)}function qj(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...y]=_;const N=s[b][1];Tp(N)&&Tp(v)&&(v=_f(!0,N,v)),s[b]=[d,v,...y]}}}}const Kj=new cm().freeze();function Sf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Cf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ov(e){if(!Tp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function zv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function iu(e){return Vj(e)?e:new Z0(e)}function Vj(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Xj(e){return typeof e=="string"||Zj(e)}function Zj(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Qj="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Pv=[],Iv={allowDangerousHtml:!0},Jj=/^(https?|ircs?|mailto|xmpp)$/i,eA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Q0(e){const t=tA(e),i=iA(e);return nA(t.runSync(t.parse(i),i),e)}function tA(e){const t=e.rehypePlugins||Pv,i=e.remarkPlugins||Pv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Iv}:Iv;return Kj().use(OT).use(i).use(Aj,s).use(t)}function iA(e){const t=e.children||"",i=new Z0;return typeof t=="string"&&(i.value=t),i}function nA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||rA;for(const _ of eA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+Qj+_.id,void 0);return om(e,d),bN(e,{Fragment:f.Fragment,components:a,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function d(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in pf)if(Object.hasOwn(pf,v)&&Object.hasOwn(_.properties,v)){const y=_.properties[v],N=pf[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(y||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function rA(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||Jj.test(e.slice(0,t))?e:""}function sA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function J0(e,t,i){const a=Uu((i||{}).ignore||[]),o=aA(t);let c=-1;for(;++c0?{type:"text",value:L}:void 0),L===!1?b.lastIndex=J+1:(y!==J&&D.push({type:"text",value:d.value.slice(y,J)}),Array.isArray(L)?D.push(...L):L&&D.push(L),y=J+P[0].length,E=!0),!b.global)break;P=b.exec(d.value)}return E?(y?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Hv(e,"(");let o=Hv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function tS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||oa(i)||Pu(i))&&(!t||i!==47)}iS.peek=RA;function wA(){this.buffer()}function CA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function kA(){this.buffer()}function EA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function NA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=pr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function TA(e){this.exit(e)}function jA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=pr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function AA(e){this.exit(e)}function RA(){return"["}function iS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function MA(){return{enter:{gfmFootnoteCallString:wA,gfmFootnoteCall:CA,gfmFootnoteDefinitionLabelString:kA,gfmFootnoteDefinition:EA},exit:{gfmFootnoteCallString:NA,gfmFootnoteCall:TA,gfmFootnoteDefinitionLabelString:jA,gfmFootnoteDefinition:AA}}}function DA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:iS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const d=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` +`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?nS:BA))),d(),p}}function BA(e,t,i){return t===0?e:nS(e,t,i)}function nS(e,t,i){return(i?"":" ")+e}const LA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];rS.peek=HA;function OA(){return{canContainEols:["delete"],enter:{strikethrough:PA},exit:{strikethrough:IA}}}function zA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:LA}],handlers:{delete:rS}}}function PA(e){this.enter({type:"delete",children:[]},e)}function IA(e){this.exit(e)}function rS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function HA(){return"~"}function UA(e){return e.length}function $A(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||UA,o=[],c=[],h=[],p=[];let d=0,_=-1;for(;++_d&&(d=e[_].length);++Ep[E])&&(p[E]=P)}N.push(D)}c[_]=N,h[_]=A}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=D),v[x]=D),b[x]=P}c.splice(1,0,b),h.splice(1,0,v),_=-1;const y=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),WA);return a(),c}function WA(e,t,i){return">"+(i?"":" ")+e}function GA(e,t){return $v(e,t.inConstruct,!0)&&!$v(e,t.notInConstruct,!1)}function $v(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function KA(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function VA(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function XA(e,t,i,s){const a=VA(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(KA(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,ZA);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(YA(o,a)+1,3)),d=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` +`,encode:["`"],...h.current()})),x()}return _+=h.move(` +`),o&&(_+=h.move(o+` +`)),_+=h.move(p),d(),_}function ZA(e,t,i){return(i?"":" ")+e}function um(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function QA(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("[");return d+=p.move(i.safe(i.associationId(e),{before:d,after:"]",...p.current()})),d+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),c(),d}function JA(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function To(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ru(e,t,i){const s=al(e),a=al(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}sS.peek=eR;function sS(e,t,i,s){const a=JA(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),_=Ru(s.before.charCodeAt(s.before.length-1),d,a);_.inside&&(p=To(d)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function eR(e,t,i){return i.options.emphasis||"*"}function tR(e,t){let i=!1;return om(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ep}),!!((!e.depth||e.depth<3)&&tm(e)&&(t.options.setext||i))}function iR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(tR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` `,after:` -`});return _(),x(),b+` +`});return x(),_(),b+` `+(a===1?"=":"-").repeat(b.length-(Math.max(b.lastIndexOf("\r"),b.lastIndexOf(` `))+1))}const c="#".repeat(a),h=i.enter("headingAtx"),p=i.enter("phrasing");o.move(c+" ");let d=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(d)&&(d=To(d.charCodeAt(0))+d.slice(1)),d=d?c+" "+d:c,i.options.closeAtx&&(d+=" "+c),p(),h(),d}sS.peek=tR;function sS(e){return e.value||""}function tR(){return"<"}aS.peek=iR;function aS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("![");return d+=p.move(i.safe(e.alt,{before:d,after:"]",...p.current()})),d+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),d+=p.move(")"),c(),d}function iR(){return"!"}lS.peek=nR;function lS(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const d=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const x=i.stack;i.stack=[],c=i.enter("reference");const _=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=x,o(),a==="full"||!d||d!==_?p+=h.move(_+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function nR(){return"!"}oS.peek=rR;function oS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}uS.peek=sR;function uS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(cS(e,i)){const x=i.stack;i.stack=[],h=i.enter("autolink");let _=c.move("<");return _+=c.move(i.containerPhrasing(e,{before:_,after:">",...c.current()})),_+=c.move(">"),h(),i.stack=x,_}h=i.enter("link"),p=i.enter("label");let d=c.move("[");return d+=c.move(i.containerPhrasing(e,{before:d,after:"](",...c.current()})),d+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),d+=c.move("<"),d+=c.move(i.safe(e.url,{before:d,after:">",...c.current()})),d+=c.move(">")):(p=i.enter("destinationRaw"),d+=c.move(i.safe(e.url,{before:d,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),d+=c.move(" "+a),d+=c.move(i.safe(e.title,{before:d,after:a,...c.current()})),d+=c.move(a),p()),d+=c.move(")"),h(),d}function sR(e,t,i){return cS(e,i)?"<":"["}hS.peek=aR;function hS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const d=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const x=i.stack;i.stack=[],c=i.enter("reference");const _=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=x,o(),a==="full"||!d||d!==_?p+=h.move(_+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function aR(){return"["}function hm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function lR(e){const t=hm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function oR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function dS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function cR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?oR(i):hm(i);const h=e.ordered?c==="."?")":".":lR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const x=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&x&&(!x.children||!x.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),dS(i)===c&&x){let _=-1;for(;++_-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),d=i.indentLines(i.containerFlow(e,h.current()),x);return p(),d;function x(_,b,v){return b?(v?"":" ".repeat(c))+_:(v?o:o+" ".repeat(c-o.length))+_}}function dR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const fR=Uu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function pR(e,t,i,s){return(e.children.some(function(c){return fR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function mR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}fS.peek=gR;function fS(e,t,i,s){const a=mR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),x=Ru(s.before.charCodeAt(s.before.length-1),d,a);x.inside&&(p=To(d)+p.slice(1));const _=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),_,a);b.inside&&(p=p.slice(0,-1)+To(_));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:x.outside},h+p+v}function gR(e,t,i){return i.options.strong||"*"}function _R(e,t,i,s){return i.safe(e.value,s)}function xR(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function bR(e,t,i){const s=(dS(i)+(i.options.ruleSpaces?" ":"")).repeat(xR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const pS={blockquote:$A,break:$v,code:KA,definition:XA,emphasis:rS,hardBreak:$v,heading:eR,html:sS,image:aS,imageReference:lS,inlineCode:oS,link:uS,linkReference:hS,list:cR,listItem:hR,paragraph:dR,root:pR,strong:fS,text:_R,thematicBreak:bR};function vR(){return{enter:{table:yR,tableData:Fv,tableHeader:Fv,tableRow:wR},exit:{codeText:CR,table:SR,tableData:Tf,tableHeader:Tf,tableRow:Tf}}}function yR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function SR(e){this.exit(e),this.data.inTable=void 0}function wR(e){this.enter({type:"tableRow",children:[]},e)}function Tf(e){this.exit(e)}function Fv(e){this.enter({type:"tableCell",children:[]},e)}function CR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,kR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function kR(e,t){return t==="|"?t:e}function ER(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,y,E,A){return d(x(v,E,A),v.align)}function h(v,y,E,A){const N=_(v,E,A),L=d([N]);return L.slice(0,L.indexOf(` -`))}function p(v,y,E,A){const N=E.enter("tableCell"),L=E.enter("phrasing"),O=E.containerPhrasing(v,{...A,before:o,after:o});return L(),N(),O}function d(v,y){return HA(v,{align:y,alignDelimiters:s,padding:i,stringLength:a})}function x(v,y,E){const A=v.children;let N=-1;const L=[],O=y.enter("table");for(;++N0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const qR={tokenize:QR,partial:!0};function WR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:VR,continuation:{tokenize:XR},exit:ZR}},text:{91:{name:"gfmFootnoteCall",tokenize:KR},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:GR,resolveTo:YR}}}}function GR(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const d=dr(s.sliceSerialize({start:c.end,end:s.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function YR(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function KR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(_){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),p}function p(_){return _!==94?i(_):(e.enter("gfmFootnoteCallMarker"),e.consume(_),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(_){if(o>999||_===93&&!c||_===null||_===91||qt(_))return i(_);if(_===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(dr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(_)}return qt(_)||(c=!0),o++,e.consume(_),_===92?x:d}function x(_){return _===91||_===92||_===93?(e.consume(_),o++,d):d(_)}}function VR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",x):i(y)}function x(y){if(c>999||y===93&&!h||y===null||y===91||qt(y))return i(y);if(y===93){e.exit("chunkString");const E=e.exit("gfmFootnoteDefinitionLabelString");return o=dr(s.sliceSerialize(E)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(y)||(h=!0),c++,e.consume(y),y===92?_:x}function _(y){return y===91||y===92||y===93?(e.consume(y),c++,x):x(y)}function b(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),a.includes(o)||a.push(o),Ct(e,v,"gfmFootnoteDefinitionWhitespace")):i(y)}function v(y){return t(y)}}function XR(e,t,i){return e.check(Lo,t,e.attempt(qR,t,i))}function ZR(e){e.exit("gfmFootnoteDefinition")}function QR(e,t,i){const s=this;return Ct(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function JR(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(y):(c.consume(y),_++,v);if(_<2&&!i)return p(y);const A=c.exit("strikethroughSequenceTemporary"),N=ll(y);return A._open=!N||N===2&&!!E,A._close=!E||E===2&&!!N,h(y)}}}class e3{constructor(){this.map=[]}add(t,i,s){t3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function t3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Z=s.events[se][1].type;if(Z==="lineEnding"||Z==="linePrefix")se--;else break}const W=se>-1?s.events[se][1].type:null,G=W==="tableHead"||W==="tableRow"?M:p;return G===M&&s.parser.lazy[s.now().line]?i(U):G(U)}function p(U){return e.enter("tableHead"),e.enter("tableRow"),d(U)}function d(U){return U===124||(c=!0,o+=1),x(U)}function x(U){return U===null?i(U):$e(U)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(U),e.exit("lineEnding"),v):i(U):xt(U)?Ct(e,x,"whitespace")(U):(o+=1,c&&(c=!1,a+=1),U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),c=!0,x):(e.enter("data"),_(U)))}function _(U){return U===null||U===124||qt(U)?(e.exit("data"),x(U)):(e.consume(U),U===92?b:_)}function b(U){return U===92||U===124?(e.consume(U),_):_(U)}function v(U){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(U):(e.enter("tableDelimiterRow"),c=!1,xt(U)?Ct(e,y,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):y(U))}function y(U){return U===45||U===58?A(U):U===124?(c=!0,e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),E):$(U)}function E(U){return xt(U)?Ct(e,A,"whitespace")(U):A(U)}function A(U){return U===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),N):U===45?(o+=1,N(U)):U===null||$e(U)?J(U):$(U)}function N(U){return U===45?(e.enter("tableDelimiterFiller"),L(U)):$(U)}function L(U){return U===45?(e.consume(U),L):U===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),O):(e.exit("tableDelimiterFiller"),O(U))}function O(U){return xt(U)?Ct(e,J,"whitespace")(U):J(U)}function J(U){return U===124?y(U):U===null||$e(U)?!c||a!==o?$(U):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(U)):$(U)}function $(U){return i(U)}function M(U){return e.enter("tableRow"),X(U)}function X(U){return U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),X):U===null||$e(U)?(e.exit("tableRow"),t(U)):xt(U)?Ct(e,X,"whitespace")(U):(e.enter("data"),he(U))}function he(U){return U===null||U===124||qt(U)?(e.exit("data"),X(U)):(e.consume(U),U===92?ye:he)}function ye(U){return U===92||U===124?(e.consume(U),he):he(U)}}function s3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,d,x,_;const b=new e3;for(;++ii[2]+1){const y=i[2]+1,E=i[3]-i[2]-1;e.add(y,E,[])}}e.add(i[3]+1,0,[["exit",_,t]])}return a!==void 0&&(o.end=Object.assign({},tl(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Wv(e,t,i,s,a){const o=[],c=tl(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function tl(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const a3={name:"tasklistCheck",tokenize:o3};function l3(){return{text:{91:a3}}}function o3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return $e(p)?t(p):xt(p)?e.check({tokenize:c3},t,i)(p):i(p)}}function c3(e,t,i){return Ct(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function u3(e){return A0([LR(),WR(),JR(e),n3(),l3()])}const h3={};function wS(e){const t=this,i=e||h3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(u3(i)),o.push(RR()),c.push(MR(i))}const ta=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ol={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ta,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ta],h2:[["className","sr-only"]],img:[...ta,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ta,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ta],table:[...ta],ul:[...ta,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},As={}.hasOwnProperty;function d3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ol,...t}:ol,stack:[]},a=CS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function CS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return f3(e,i);case"doctype":return p3(e,i);case"element":return m3(e,i);case"root":return g3(e,i);case"text":return _3(e,i)}}}function f3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return zo(o,t),o}}function p3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return zo(i,t),i}}function m3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=kS(e,t.children),a=x3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&As.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let d=-1;for(;++d4&&t.slice(0,4).toLowerCase()==="data")return i}function NS(e){return function(t){return d3(t,e)}}const rl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],Xr=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function TS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const y3=Object.fromEntries(rl.map(e=>[TS(e),e])),S3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function bu(e){if(!e)return null;const t=TS(e.trim());return t?y3[t]??S3[t]??null:null}function jS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function AS(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(jS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function Rp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=AS(e,t,i);return h||!c&&!o?f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:f.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?f.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:f.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function Kv(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function ru(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),d=Math.max(1,i-2*h),x=Math.max(1,s-2*p),_=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,_)),v=E=>{const A=a.hasSpeaker?E*c:0,N=a.hasSpeaker?A*o:0,L=Math.max(1,x-N),O=a.fontWeight??400,J=Kv((X,he)=>e(X,he,O),t,d,E),$=J.length*E*o,M=J.every(X=>e(X,E,O)<=d+.5);return{lines:J,ok:$<=L&&M}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const E=Math.max(1,a.fontSize),{lines:A,ok:N}=v(E);return{lines:A,fontSize:E,lineHeight:E*o,speakerFontSize:a.hasSpeaker?E*c:0,overflow:!N}}for(let E=_;E>=b;E-=.5){const{lines:A,ok:N}=v(E);if(N)return{lines:A,fontSize:E,lineHeight:E*o,speakerFontSize:a.hasSpeaker?E*c:0,overflow:!1}}return{lines:Kv(e,t,d,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function w3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const RS=["speech","narration","sfx"],C3=2;function Cr(e,t,i){return Math.min(i,Math.max(t,e))}function sl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Cr(e,t,i):void 0}function fm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=sl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=sl(t.lineHeightFactor,.9,2),c=sl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Fu(e){if(!e||typeof e!="object")return;const t=e,i=sl(t.paddingX,0,.25),s=sl(t.paddingY,0,.25),a=sl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function su(e,t,i,s){const{minFontSize:a,maxFontSize:o}=w3(t),c=fm(e.textStyle),h=Fu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function k3(e,t,i){const s=Fu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function MS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Vv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Cr(e,h,p):t+i/2,half:c}}function DS(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,d=t+a.y*s;if(p>=e&&p<=e+i&&d>=t&&d<=t+s)return null;const x=p-c,_=d-h,b=Math.max(6,Math.min(i,s)*.3),v=o??MS(i,s);if(Math.abs(_)>=Math.abs(x)){const N=_>=0?t+s:t,{center:L,half:O}=Vv(p,e,i,v,b);return{tip:{x:p,y:d},base1:{x:L-O,y:N},base2:{x:L+O,y:N}}}const y=x>=0?e+i:e,{center:E,half:A}=Vv(d,t,s,v,b);return{tip:{x:p,y:d},base1:{x:y,y:E-A},base2:{x:y,y:E+A}}}function E3(e){return e.type!=="speech"||!e.tailAnchor?!1:DS(0,0,1,1,e.tailAnchor)!==null}function N3(e,t,i,s,a,o){const c=o??MS(i,s),h=e+i,p=t+s,d=!!a&&a.base1.y===t&&a.base2.y===t,x=!!a&&a.base1.x===h&&a.base2.x===h,_=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return d&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),x&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),_&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function T3(e,t,i,s,a,o){const c=N3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function j3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let Xv=0;function Zv(e,t=.1,i=.1){return Xv++,{id:`overlay-${Date.now()}-${Xv}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function A3(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const au=.05;function Ii(e){return typeof e=="number"&&Number.isFinite(e)}function R3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const d=a?au:Cr(o?1-t-au:(1-t)/2,0,1),x=c?au:Cr(h?1-i-au:(1-i)/2,0,1);return{x:d,y:x}}let M3=0;function D3(e){if(!e||typeof e!="object")return null;const t=e,i=RS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ii(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ii(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ii(t.x)&&Ii(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?R3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Cr(c,0,1),h=Cr(h,0,1),a=Cr(a,.02,1),o=Cr(o,.02,1);const d={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++M3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){d.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;d.tailAnchor=b&&Ii(b.x)&&Ii(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(d.speaker=t.speaker);const x=fm(t.textStyle),_=Fu(t.bubbleStyle);return x&&(d.textStyle=x),_&&(d.bubbleStyle=_),d}function B3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&RS.includes(t.type)&&Ii(t.x)&&Ii(t.y)&&Ii(t.width)&&Ii(t.height)&&typeof t.text=="string"}function L3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=D3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),B3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function qD(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=fm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Fu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const Qv=new Set(["speech","narration"]),O3=.12;function Jv(e){return Ii(e==null?void 0:e.x)&&Ii(e==null?void 0:e.y)&&Ii(e==null?void 0:e.width)&&Ii(e==null?void 0:e.height)&&e.width>0&&e.height>0}function z3(e,t=O3){const i=[];for(let s=0;s0?d/x:0;_>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:_})}}return i}function kr(e){return e.kind==="text"}function P3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||kr(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function BS(e,t=C3){return!e.finalImagePath||!(e.overlays??[]).some(E3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ey,height:Math.round(ey*s/i)}}function lu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?f.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>f.jsxs("div",{className:"flex gap-2 text-xs",children:[f.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),f.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&f.jsx("div",{className:"border-l-2 border-border pl-3",children:f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&f.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function H3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),f.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&f.jsx(Rp,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&f.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[f.jsx(Rp,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),f.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:f.jsx(lu,{cut:e})})]}),!c&&p&&f.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?f.jsx(lu,{cut:e}):f.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&f.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[f.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[f.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),f.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&f.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),f.jsx(lu,{cut:e})]})]}),e.description&&f.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&f.jsx(lu,{cut:e}),s&&(()=>{const d=P3(e);return f.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":d.key,onClick:()=>s(e.id,d.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:d.label})})()]})}function U3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,d]=w.useState(null),x=t.replace(/\.md$/,""),_=w.useCallback(async()=>{h(!0),d(null);try{const b=await i(`/api/stories/${e}/cuts/${x}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const y=await b.json();d(y.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{d("Failed to load cuts")}finally{h(!1)}},[i,e,x]);return w.useEffect(()=>{_();const b=setInterval(_,5e3);return()=>clearInterval(b)},[_]),c&&!a?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:p}),f.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[x,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),f.jsx("button",{onClick:_,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):f.jsx("div",{className:"h-full overflow-y-auto",children:f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>f.jsx(H3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const ty=/!\[[^\]]*\]\([^)]*\)/g,$3=//g,LS=200;function F3(e){const t=(e.match(ty)||[]).length,i=e.length,s=e.replace($3," ").replace(ty," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,LS)}}function q3(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const W3=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function G3(e){for(const t of W3){const i=e.match(t);if(i)return i[0]}return null}function pm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());_.length===0?i.push(`${p}: block has no image reference`):_.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&_[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=G3(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function zS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(Y3(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=OS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const jf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function K3(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,d)=>p-d);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function PS(e){const t=c=>{var h;return((h=jf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...jf.map(c=>c.key),"other"],a=c=>{var h;return((h=jf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:K3(h)})}return o}const V3=220,Af=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function mm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.length_.trim()).filter(Boolean),p=h.filter(_=>/^([-*+]|\d+[.)])\s/.test(_)||Af.test(_)).length,d=c.split(/\n\s*\n/).map(_=>_.trim()).filter(Boolean),x=d.some(_=>_.length>=120&&!/^([-*+]|\d+[.)])\s/.test(_)&&!Af.test(_));h.length>0&&p/h.length>=.5||!x?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):d.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Af.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function X3(e){return/\.(webp|jpe?g)$/i.test(e)}function Mp(e){var c;let t=0,i=0,s=0,a=0,o=0;for(const h of e)kr(h)||(t++,h.cleanImagePath&&X3(h.cleanImagePath)&&(i++,(((c=h.overlays)==null?void 0:c.length)??0)>0&&s++)),h.finalImagePath&&h.exportedAt&&a++,h.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const Z3={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function ou(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function Q3(e){const{cuts:t,published:i=!1}=e,s=Mp(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.needClean,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,x={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},_=["plan","clean","letter","export","upload","publish"],b=_.findIndex(L=>!x[L]),v=L=>s.needClean>0?ou(L,s.needClean):"no image cuts",y={plan:ou(s.total,s.total),clean:v(s.withClean),letter:v(s.withText),export:ou(s.exported,s.total),upload:ou(s.uploaded,s.total),publish:null},E=_.map((L,O)=>({key:L,label:Z3[L],status:b===-1||OLS,a=tM({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[f.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[f.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),f.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),f.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${nM[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[f.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&f.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&f.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&f.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[f.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),f.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),f.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Z0,{remarkPlugins:[J0,wS],rehypePlugins:[[NS,iM]],children:e})}):f.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const sM="modulepreload",aM=function(e){return"/"+e},iy={},ny=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(d){return Promise.all(d.map(x=>Promise.resolve(x).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(d=>{if(d=aM(d),d in iy)return;iy[d]=!0;const x=d.endsWith(".css"),_=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${_}`))return;const b=document.createElement("link");if(b.rel=x?"stylesheet":sM,x||(b.as="script"),b.crossOrigin="",b.href=d,p&&b.setAttribute("nonce",p),document.head.appendChild(b),x)return new Promise((v,y)=>{b.addEventListener("load",v),b.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},gm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],lM="system-ui, sans-serif",oM=gm.find(e=>e.family==="Noto Sans"),cM=gm.find(e=>e.category==="display");function uM(e){return gm.find(i=>i.category==="body"&&i.languages.includes(e))||oM}function hM(){return cM}function dM(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function ry(e){return`"${e.family}", ${lM}`}function fM(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function vu(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function pM(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==vu(e.current)}function IS(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function Sn(e,t){return e*t}function sy(e,t){return t===0?0:e/t}function ay(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=dM(e),document.head.appendChild(i)}const yu={speech:"Speech",narration:"Narration",sfx:"SFX"},mM={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Rf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:yu[e.type]}const ly=.05,gM=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function cu(e,t,i){return Math.min(i,Math.max(t,e))}function _M({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h}){var hi,re,xe,Pe,Fe,Qe;const p=uM(c),d=hM(),x=ry(p),_=ry(d);w.useEffect(()=>{ay(p),ay(d)},[p,d]),w.useEffect(()=>{let H=!1;return ye(!1),(async()=>{try{const{ensureFontsReady:ge}=await ny(async()=>{const{ensureFontsReady:Te}=await import("./export-cut-DRQwImdk.js");return{ensureFontsReady:Te}},[]);await ge([p.family,d.family])}catch{}H||ye(!0)})(),()=>{H=!0}},[p.family,d.family]);const b=AS(e,t.cleanImagePath,h),v=w.useMemo(()=>L3(t.overlays),[t.overlays]),y=v.invalid.length,[E,A]=w.useState(!1),N=y===0&&v.changed&&v.overlays.length>0,[L,O]=w.useState(()=>v.overlays),[J,$]=w.useState(()=>vu(v.overlays)),M=w.useRef(null),X=w.useCallback(H=>(ge,Te,me=400)=>{var Oe;!M.current&&typeof document<"u"&&(M.current=document.createElement("canvas"));const He=(Oe=M.current)==null?void 0:Oe.getContext("2d");return He?(He.font=`${me} ${Te}px ${H}`,He.measureText(ge).width):ge.length*Te*.5},[]),[he,ye]=w.useState(!1),[U,se]=w.useState(null),[W,G]=w.useState(!1),[Z,I]=w.useState(!1),[j,z]=w.useState(null),[B,_e]=w.useState({x:0,y:0,width:0,height:0}),T=w.useRef(null),R=w.useRef(null),Y=w.useRef(null),C=w.useCallback(()=>{const H=T.current;if(!H)return;const ge=H.clientWidth,Te=H.clientHeight;let me,He;if(t.kind==="text"){const Dt=I3(t.aspectRatio)??{width:800,height:600};me=Dt.width,He=Dt.height}else{const Dt=R.current;if(!Dt||!Dt.naturalWidth)return;me=Dt.naturalWidth,He=Dt.naturalHeight}if(!ge||!Te)return;const Oe=Math.min(ge/me,Te/He),ut=me*Oe,it=He*Oe;_e({x:(ge-ut)/2,y:(Te-it)/2,width:ut,height:it})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=T.current;if(!H)return;const ge=new ResizeObserver(()=>C());return ge.observe(H),()=>ge.disconnect()},[C]);const ae=w.useCallback(H=>{const ge=A3(H.type,H.x,H.y),Te=ge.width,me=Math.max(.08,1-H.y);if(!H.text||!he||B.width<=0)return ge;const He=H.type==="sfx"?_:x,Oe=Sn(Te,B.width);let ut=H.type==="sfx"?.08:.12;for(let it=0;it<24;it++){const Dt=Math.min(ut,me),Bt=Sn(Dt,B.height);if(!ru(X(He),H.text,Oe,Bt,su({...H},B.height||300,Oe,Bt)).overflow||Dt>=me)return{width:Te,height:Dt};ut+=.03}return{width:Te,height:Math.min(ut,me)}},[he,B,X,x,_]),ie=w.useCallback(H=>{const ge=Zv(H,.1+Math.random()*.3,.1+Math.random()*.3),Te={...ge,...ae(ge)};O(me=>[...me,Te]),se(Te.id)},[ae]),oe=w.useCallback(H=>{const Te={...Zv(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},me={...Te,...ae(Te)};O(He=>[...He,me]),se(me.id)},[ae]),F=w.useCallback((H,ge)=>{O(Te=>Te.map(me=>me.id===H?{...me,...ge}:me))},[]),ue=w.useCallback(H=>{var ut;const ge=B.height||300,Te=B.width>0?Sn(H.width,B.width):200,me=B.height>0?Sn(H.height,B.height):100,He=H.type==="sfx"?_:x,Oe=ru(X(He),H.text,Te,me,su({...H,textStyle:void 0},ge,Te,me));F(H.id,{textStyle:{mode:"manual",fontScale:Oe.fontSize/Math.max(1,ge),fontWeight:((ut=H.textStyle)==null?void 0:ut.fontWeight)??400,lineHeightFactor:Oe.fontSize>0?Oe.lineHeight/Oe.fontSize:1.2,speakerScale:Oe.fontSize>0&&Oe.speakerFontSize>0?Oe.speakerFontSize/Oe.fontSize:.8}})},[B,_,x,X,F]),be=w.useCallback(H=>{O(ge=>ge.filter(Te=>Te.id!==H)),se(null),G(!1)},[]),De=w.useCallback(()=>{se(null),G(!1)},[]),Ee=w.useCallback((H,ge)=>{H.stopPropagation(),se(ge),G(!1)},[]),Be=w.useCallback((H,ge,Te)=>{H.stopPropagation(),H.preventDefault();const me=L.find(He=>He.id===ge);me&&(se(ge),Y.current={id:ge,mode:Te,startX:H.clientX,startY:H.clientY,origX:me.x,origY:me.y,origW:me.width,origH:me.height})},[L]);w.useEffect(()=>{const H=Te=>{const me=Y.current;if(!me||B.width===0)return;const He=sy(Te.clientX-me.startX,B.width),Oe=sy(Te.clientY-me.startY,B.height);if(me.mode==="move"){const ut=cu(me.origX+He,0,1-me.origW),it=cu(me.origY+Oe,0,1-me.origH);F(me.id,{x:ut,y:it})}else{const ut=cu(me.origW+He,ly,1-me.origX),it=cu(me.origH+Oe,ly,1-me.origY);F(me.id,{width:ut,height:it})}},ge=()=>{Y.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",ge),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",ge)}},[B,F]);const je=w.useCallback(()=>{s(L)},[L,s]),Ze=w.useCallback(async()=>{if(y>0&&!E){const H=y;z(`${H} overlay${H===1?"":"s"} from the cut plan ${H===1?"has":"have"} no usable position and cannot be exported — re-place ${H===1?"it":"them"} or discard ${H===1?"it":"them"} first.`);return}I(!0),z(null);try{await s(L);const{exportCut:H,ensureFontsReady:ge}=await ny(async()=>{const{exportCut:kt,ensureFontsReady:Ci}=await import("./export-cut-DRQwImdk.js");return{exportCut:kt,ensureFontsReady:Ci}},[]),Te=L.some(kt=>kt.type==="sfx"),me=[p.family,...Te?[d.family]:[]],{ready:He,missing:Oe}=await ge(me);if(!He){z(`Fonts not loaded: ${Oe.join(", ")}. Check your connection and retry.`),I(!1);return}if(t.cleanImagePath&&!b.url){z(b.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),I(!1);return}const ut=b.url,it=await H(ut,L,x,_,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),Dt=new FormData,Bt=it.type==="image/webp"?"webp":"jpg";Dt.append("file",it,`cut-${t.id}.${Bt}`);const di=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:Dt});if(di.ok)$(vu(L)),o==null||o();else{const kt=await di.json();z(kt.error||"Export failed")}}catch(H){z(H instanceof Error?H.message:"Export failed")}finally{I(!1)}},[t,b,L,e,i,p,d,x,_,h,s,o,y,E]),we=L.find(H=>H.id===U),tt=w.useMemo(()=>z3(L),[L]),mt=w.useRef(t.id);w.useEffect(()=>{mt.current!==t.id&&(mt.current=t.id,$(vu(v.overlays)))},[t.id,v.overlays]);const Ge=pM({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:J,current:L}),Ae=w.useMemo(()=>fM({...t,overlays:L},{staleExport:Ge}),[t,L,Ge]),Ve=w.useMemo(()=>IS(t),[t]),Mt=w.useMemo(()=>{const H={};for(const ge of L){const Te=j3(ge);let me=!1;if(he&&B.width>0&&ge.text){const He=ge.type==="sfx"?_:x,Oe=Sn(ge.width,B.width),ut=Sn(ge.height,B.height);me=ru(X(He),ge.text,Oe,ut,su(ge,B.height||300,Oe,ut)).overflow}(Te||me)&&(H[ge.id]={outOfBounds:Te,overflow:me})}return H},[L,he,B,X,x,_]),zt=Object.keys(Mt).length,ai=t.kind==="text",wt=!t.cleanImagePath;return!ai&&wt&&L.length===0&&!t.narration&&!((hi=t.dialogue)!=null&&hi.length)?f.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-xs font-mono text-muted",children:["Cut #",t.id]}),f.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[L.length," overlays"]}),f.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[f.jsx("button",{onClick:()=>ie("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),f.jsx("button",{onClick:()=>ie("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),f.jsx("button",{onClick:()=>ie("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[j&&f.jsx("span",{className:"text-[10px] text-error",children:j}),f.jsx("button",{onClick:Ze,disabled:Z,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:Z?"Exporting...":"Export"}),f.jsx("button",{onClick:je,className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim",children:"Save"}),f.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded",children:"Close"})]})]}),y>0&&!E?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[f.jsxs("span",{children:[y," overlay",y===1?"":"s"," from the cut plan ",y===1?"has":"have"," no usable position and cannot be exported. Re-place ",y===1?"it":"them",", or"]}),f.jsxs("button",{onClick:()=>A(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",y," unplaceable overlay",y===1?"":"s"]})]}):y>0?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",y," unplaceable overlay",y===1?"":"s"," — the export will not include ",y===1?"it":"them","."]}):N?f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,tt.length>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",tt.length," bubble ",tt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",tt.map(H=>`#${H.indexA+1} ${Rf(L[H.indexA])} ↔ #${H.indexB+1} ${Rf(L[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),f.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",Ae.hasCleanImage],["script-text","Script text",Ae.hasScriptText],["bubbles",`Bubbles placed${Ae.bubblesPlaced?` (${Ae.bubblesPlaced})`:""}`,Ae.bubblesPlaced>0],["exported","Final exported",Ae.exported],["uploaded","Uploaded",Ae.uploaded]].map(([H,ge,Te])=>f.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Te?"true":"false",className:`flex items-center gap-1 ${Te?"text-green-700":"text-muted/70"}`,children:[f.jsx("span",{"aria-hidden":!0,children:Te?"✓":"○"}),ge]},H))}),Ge&&f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),zt>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[zt," bubble",zt===1?"":"s"," may not export cleanly:"," ",Object.entries(Mt).map(([H,ge])=>{const Te=L.findIndex(He=>He.id===H),me=[ge.outOfBounds?"outside image":null,ge.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Te+1} ${Rf(L[Te])} (${me})`}).join("; "),". Resize or reposition before exporting."]}),f.jsxs("div",{className:"flex-1 min-h-0 flex",children:[f.jsxs("div",{ref:T,className:"flex-1 min-w-0 relative overflow-hidden",onClick:De,"data-testid":"editor-surface",children:[t.cleanImagePath&&b.error?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!b.url?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?f.jsx("img",{ref:R,src:b.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:C}):ai?B.width>0&&f.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:B.x,top:B.y,width:B.width,height:B.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):f.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&B.width===0){const ge=H.getBoundingClientRect();ge.width>0&&_e({x:0,y:0,width:ge.width,height:ge.height})}},children:"Narration cut"}),B.width>0&&f.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:L.map(H=>{if(H.type!=="speech")return null;const ge=B.x+Sn(H.x,B.width),Te=B.y+Sn(H.y,B.height),me=Sn(H.width,B.width),He=Sn(H.height,B.height),Oe=k3(H,me,He),ut=H.tailAnchor?DS(ge,Te,me,He,H.tailAnchor,Oe):null,it=Math.max(1.5,B.height*.004),Dt=H.id===U;return f.jsx("path",{"data-testid":`balloon-${H.id}`,d:T3(ge,Te,me,He,ut,Oe),className:`fill-white/95 ${Dt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:Dt?it+.5:it,strokeLinejoin:"round"},H.id)})}),B.width>0&&L.map(H=>{const ge=B.x+Sn(H.x,B.width),Te=B.y+Sn(H.y,B.height),me=Sn(H.width,B.width),He=Sn(H.height,B.height),Oe=H.id===U,ut=H.type==="speech",it=H.type==="narration",Dt=!!Mt[H.id];return f.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":Dt?"true":"false",onClick:Bt=>Ee(Bt,H.id),onMouseDown:Bt=>Be(Bt,H.id,"move"),className:`absolute rounded cursor-move select-none ${ut?"":`border-2 ${mM[H.type]}`} ${it?"bg-[#f4efe6]/85 rounded-md":""} ${Oe&&!ut?"ring-2 ring-accent":""} ${Dt?"ring-2 ring-amber-500":""}`,style:{left:ge,top:Te,width:me,height:He},children:[(()=>{var Ci,fi;const Bt=H.type==="sfx"?_:x;if(!H.text)return f.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:yu[H.type]});const di=H.type!=="sfx"&&!!H.speaker;if(!he)return f.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Bt,fontSize:Math.max(9,Math.min(He*.05,16)),fontWeight:((Ci=H.textStyle)==null?void 0:Ci.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:di?`${H.speaker}: ${H.text}`:H.text});const kt=ru(X(Bt),H.text,me,He,su(H,B.height,me,He));return f.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Bt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[di&&f.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:kt.speakerFontSize,lineHeight:1.2},children:H.speaker}),f.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:kt.fontSize,lineHeight:`${kt.lineHeight}px`,fontWeight:((fi=H.textStyle)==null?void 0:fi.fontWeight)??400},children:kt.lines.map((Gt,fn)=>f.jsx("span",{className:"block",children:Gt},fn))})]})})(),Oe&&f.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),Be(Bt,H.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${H.id}`})]},H.id)})]}),f.jsxs("div",{className:"w-52 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[Ve.length>0&&f.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),f.jsx("div",{className:"flex flex-col gap-1",children:Ve.map(H=>f.jsxs("button",{onClick:()=>oe(H),"data-testid":`script-insert-${H.key}`,title:`Add ${H.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[f.jsxs("span",{className:"font-medium text-accent",children:["+ ",yu[H.type]]})," ",f.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),we?f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-xs font-medium text-foreground",children:yu[we.type]}),we.speaker!==void 0&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),f.jsx("input",{value:we.speaker||"",onChange:H=>F(we.id,{speaker:H.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),f.jsx("textarea",{value:we.text,onChange:H=>F(we.id,{text:H.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),f.jsx("button",{onClick:()=>F(we.id,ae(we)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((re=we.textStyle)==null?void 0:re.mode)==="manual"?f.jsx("button",{type:"button",onClick:()=>F(we.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):f.jsx("button",{type:"button",onClick:()=>ue(we),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((xe=we.textStyle)==null?void 0:xe.mode)==="manual"?f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),f.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((we.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>F(we.id,{textStyle:{...we.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(H.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),f.jsxs("select",{value:String(we.textStyle.fontWeight??400),onChange:H=>F(we.id,{textStyle:{...we.textStyle,mode:"manual",fontWeight:H.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[f.jsx("option",{value:"400",children:"Regular"}),f.jsx("option",{value:"700",children:"Bold"})]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),f.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(we.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>F(we.id,{textStyle:{...we.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(H.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),we.type!=="sfx"&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),f.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(we.textStyle.speakerScale??.8).toFixed(2),onChange:H=>F(we.id,{textStyle:{...we.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(H.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):f.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),we.type==="speech"&&(()=>{const H=we.tailAnchor||{x:.5,y:1.2};return f.jsxs("div",{className:"space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),f.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:gM.map(ge=>f.jsx("button",{type:"button",onClick:()=>F(we.id,{tailAnchor:ge.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${ge.key}`,children:ge.label},ge.key))}),f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",f.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:ge=>F(we.id,{tailAnchor:{...H,x:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",f.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:ge=>F(we.id,{tailAnchor:{...H,y:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),we.type!=="sfx"&&f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Pe=we.bubbleStyle)==null?void 0:Pe.paddingX)??.06)*100).toFixed(0),onChange:H=>F(we.id,{bubbleStyle:{...we.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Fe=we.bubbleStyle)==null?void 0:Fe.paddingY)??.08)*100).toFixed(0),onChange:H=>F(we.id,{bubbleStyle:{...we.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Qe=we.bubbleStyle)==null?void 0:Qe.cornerRadius)??.4)*100).toFixed(0),onChange:H=>F(we.id,{bubbleStyle:{...we.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(H.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),f.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font: ",we.type==="sfx"?d.family:p.family]}),f.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[f.jsxs("p",{children:["x: ",we.x.toFixed(3),", y: ",we.y.toFixed(3)]}),f.jsxs("p",{children:["w: ",we.width.toFixed(3),", h: ",we.height.toFixed(3)]})]}),f.jsx("button",{onClick:()=>{W?be(we.id):G(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:W?"Click again to delete":"Delete"})]}):f.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const xM={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},bM="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",vM="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function yM(e){var a;const t=xM[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(vM),s.push(bM),s.join(` -`).trim()}function SM(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function oy(e,t){const i=SM(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",yM(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` -`)}function wM(e,t){const i=`${t}.cuts.json`,s=IS(e),a=s.length>0?s.map(o=>o.type==="speech"?`- speech — ${o.speaker||"Speaker"}: "${o.text}"`:o.type==="narration"?`- narration: ${o.text}`:`- sfx: ${o.text}`).join(` +`,...o.current()});return/^[\t ]/.test(d)&&(d=To(d.charCodeAt(0))+d.slice(1)),d=d?c+" "+d:c,i.options.closeAtx&&(d+=" "+c),p(),h(),d}aS.peek=nR;function aS(e){return e.value||""}function nR(){return"<"}lS.peek=rR;function lS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("![");return d+=p.move(i.safe(e.alt,{before:d,after:"]",...p.current()})),d+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),d+=p.move(")"),c(),d}function rR(){return"!"}oS.peek=sR;function oS(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const d=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!d||d!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function sR(){return"!"}cS.peek=aR;function cS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}hS.peek=lR;function hS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(uS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let d=c.move("[");return d+=c.move(i.containerPhrasing(e,{before:d,after:"](",...c.current()})),d+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),d+=c.move("<"),d+=c.move(i.safe(e.url,{before:d,after:">",...c.current()})),d+=c.move(">")):(p=i.enter("destinationRaw"),d+=c.move(i.safe(e.url,{before:d,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),d+=c.move(" "+a),d+=c.move(i.safe(e.title,{before:d,after:a,...c.current()})),d+=c.move(a),p()),d+=c.move(")"),h(),d}function lR(e,t,i){return uS(e,i)?"<":"["}dS.peek=oR;function dS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const d=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!d||d!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function oR(){return"["}function hm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function cR(e){const t=hm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function uR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function fS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function hR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?uR(i):hm(i);const h=e.ordered?c==="."?")":".":cR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),fS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),d=i.indentLines(i.containerFlow(e,h.current()),_);return p(),d;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function pR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const mR=Uu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function gR(e,t,i,s){return(e.children.some(function(c){return mR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function xR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}pS.peek=_R;function pS(e,t,i,s){const a=xR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),_=Ru(s.before.charCodeAt(s.before.length-1),d,a);_.inside&&(p=To(d)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function _R(e,t,i){return i.options.strong||"*"}function bR(e,t,i,s){return i.safe(e.value,s)}function vR(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function yR(e,t,i){const s=(fS(i)+(i.options.ruleSpaces?" ":"")).repeat(vR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const mS={blockquote:qA,break:Fv,code:XA,definition:QA,emphasis:sS,hardBreak:Fv,heading:iR,html:aS,image:lS,imageReference:oS,inlineCode:cS,link:hS,linkReference:dS,list:hR,listItem:fR,paragraph:pR,root:gR,strong:pS,text:bR,thematicBreak:yR};function SR(){return{enter:{table:wR,tableData:qv,tableHeader:qv,tableRow:kR},exit:{codeText:ER,table:CR,tableData:Tf,tableHeader:Tf,tableRow:Tf}}}function wR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function CR(e){this.exit(e),this.data.inTable=void 0}function kR(e){this.enter({type:"tableRow",children:[]},e)}function Tf(e){this.exit(e)}function qv(e){this.enter({type:"tableCell",children:[]},e)}function ER(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,NR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function NR(e,t){return t==="|"?t:e}function TR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,y,N,A){return d(_(v,N,A),v.align)}function h(v,y,N,A){const E=x(v,N,A),D=d([E]);return D.slice(0,D.indexOf(` +`))}function p(v,y,N,A){const E=N.enter("tableCell"),D=N.enter("phrasing"),P=N.containerPhrasing(v,{...A,before:o,after:o});return D(),E(),P}function d(v,y){return $A(v,{align:y,alignDelimiters:s,padding:i,stringLength:a})}function _(v,y,N){const A=v.children;let E=-1;const D=[],P=y.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const GR={tokenize:e3,partial:!0};function YR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ZR,continuation:{tokenize:QR},exit:JR}},text:{91:{name:"gfmFootnoteCall",tokenize:XR},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:KR,resolveTo:VR}}}}function KR(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const d=pr(s.sliceSerialize({start:c.end,end:s.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function VR(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function XR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(x){if(o>999||x===93&&!c||x===null||x===91||Ft(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(pr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Ft(x)||(c=!0),o++,e.consume(x),x===92?_:d}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,d):d(x)}}function ZR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(y)}function _(y){if(c>999||y===93&&!h||y===null||y===91||Ft(y))return i(y);if(y===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Ft(y)||(h=!0),c++,e.consume(y),y===92?x:_}function x(y){return y===91||y===92||y===93?(e.consume(y),c++,_):_(y)}function b(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),a.includes(o)||a.push(o),Ct(e,v,"gfmFootnoteDefinitionWhitespace")):i(y)}function v(y){return t(y)}}function QR(e,t,i){return e.check(Lo,t,e.attempt(GR,t,i))}function JR(e){e.exit("gfmFootnoteDefinition")}function e3(e,t,i){const s=this;return Ct(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function t3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(y):(c.consume(y),x++,v);if(x<2&&!i)return p(y);const A=c.exit("strikethroughSequenceTemporary"),E=al(y);return A._open=!E||E===2&&!!N,A._close=!N||N===2&&!!E,h(y)}}}class i3{constructor(){this.map=[]}add(t,i,s){n3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function n3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const X=s.events[re][1].type;if(X==="lineEnding"||X==="linePrefix")re--;else break}const W=re>-1?s.events[re][1].type:null,G=W==="tableHead"||W==="tableRow"?L:p;return G===L&&s.parser.lazy[s.now().line]?i(U):G(U)}function p(U){return e.enter("tableHead"),e.enter("tableRow"),d(U)}function d(U){return U===124||(c=!0,o+=1),_(U)}function _(U){return U===null?i(U):$e(U)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(U),e.exit("lineEnding"),v):i(U):xt(U)?Ct(e,_,"whitespace")(U):(o+=1,c&&(c=!1,a+=1),U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(U)))}function x(U){return U===null||U===124||Ft(U)?(e.exit("data"),_(U)):(e.consume(U),U===92?b:x)}function b(U){return U===92||U===124?(e.consume(U),x):x(U)}function v(U){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(U):(e.enter("tableDelimiterRow"),c=!1,xt(U)?Ct(e,y,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):y(U))}function y(U){return U===45||U===58?A(U):U===124?(c=!0,e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),N):q(U)}function N(U){return xt(U)?Ct(e,A,"whitespace")(U):A(U)}function A(U){return U===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),E):U===45?(o+=1,E(U)):U===null||$e(U)?J(U):q(U)}function E(U){return U===45?(e.enter("tableDelimiterFiller"),D(U)):q(U)}function D(U){return U===45?(e.consume(U),D):U===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),P):(e.exit("tableDelimiterFiller"),P(U))}function P(U){return xt(U)?Ct(e,J,"whitespace")(U):J(U)}function J(U){return U===124?y(U):U===null||$e(U)?!c||a!==o?q(U):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(U)):q(U)}function q(U){return i(U)}function L(U){return e.enter("tableRow"),Z(U)}function Z(U){return U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),Z):U===null||$e(U)?(e.exit("tableRow"),t(U)):xt(U)?Ct(e,Z,"whitespace")(U):(e.enter("data"),he(U))}function he(U){return U===null||U===124||Ft(U)?(e.exit("data"),Z(U)):(e.consume(U),U===92?ye:he)}function ye(U){return U===92||U===124?(e.consume(U),he):he(U)}}function l3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,d,_,x;const b=new i3;for(;++ii[2]+1){const y=i[2]+1,N=i[3]-i[2]-1;e.add(y,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},el(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Gv(e,t,i,s,a){const o=[],c=el(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function el(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const o3={name:"tasklistCheck",tokenize:u3};function c3(){return{text:{91:o3}}}function u3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return Ft(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return $e(p)?t(p):xt(p)?e.check({tokenize:h3},t,i)(p):i(p)}}function h3(e,t,i){return Ct(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function d3(e){return R0([zR(),YR(),t3(e),s3(),c3()])}const f3={};function CS(e){const t=this,i=e||f3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(d3(i)),o.push(DR()),c.push(BR(i))}const ta=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ll={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ta,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ta],h2:[["className","sr-only"]],img:[...ta,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ta,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ta],table:[...ta],ul:[...ta,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},As={}.hasOwnProperty;function p3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ll,...t}:ll,stack:[]},a=kS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function kS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return m3(e,i);case"doctype":return g3(e,i);case"element":return x3(e,i);case"root":return _3(e,i);case"text":return b3(e,i)}}}function m3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return zo(o,t),o}}function g3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return zo(i,t),i}}function x3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=ES(e,t.children),a=v3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&As.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let d=-1;for(;++d4&&t.slice(0,4).toLowerCase()==="data")return i}function TS(e){return function(t){return p3(t,e)}}const nl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],Xr=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function jS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const w3=Object.fromEntries(nl.map(e=>[jS(e),e])),C3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function bu(e){if(!e)return null;const t=jS(e.trim());return t?w3[t]??C3[t]??null:null}function AS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function RS(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(AS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function Rp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=RS(e,t,i);return h||!c&&!o?f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:f.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?f.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:f.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function Vv(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function ru(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),d=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=N=>{const A=a.hasSpeaker?N*c:0,E=a.hasSpeaker?A*o:0,D=Math.max(1,_-E),P=a.fontWeight??400,J=Vv((Z,he)=>e(Z,he,P),t,d,N),q=J.length*N*o,L=J.every(Z=>e(Z,N,P)<=d+.5);return{lines:J,ok:q<=D&&L}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:A,ok:E}=v(N);return{lines:A,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:A,ok:E}=v(N);if(E)return{lines:A,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:Vv(e,t,d,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function k3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const MS=["speech","narration","sfx"],E3=2;function kr(e,t,i){return Math.min(i,Math.max(t,e))}function rl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?kr(e,t,i):void 0}function fm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=rl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=rl(t.lineHeightFactor,.9,2),c=rl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Fu(e){if(!e||typeof e!="object")return;const t=e,i=rl(t.paddingX,0,.25),s=rl(t.paddingY,0,.25),a=rl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function su(e,t,i,s){const{minFontSize:a,maxFontSize:o}=k3(t),c=fm(e.textStyle),h=Fu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function N3(e,t,i){const s=Fu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function DS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Xv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?kr(e,h,p):t+i/2,half:c}}function BS(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,d=t+a.y*s;if(p>=e&&p<=e+i&&d>=t&&d<=t+s)return null;const _=p-c,x=d-h,b=Math.max(6,Math.min(i,s)*.3),v=o??DS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:D,half:P}=Xv(p,e,i,v,b);return{tip:{x:p,y:d},base1:{x:D-P,y:E},base2:{x:D+P,y:E}}}const y=_>=0?e+i:e,{center:N,half:A}=Xv(d,t,s,v,b);return{tip:{x:p,y:d},base1:{x:y,y:N-A},base2:{x:y,y:N+A}}}function T3(e){return e.type!=="speech"||!e.tailAnchor?!1:BS(0,0,1,1,e.tailAnchor)!==null}function j3(e,t,i,s,a,o){const c=o??DS(i,s),h=e+i,p=t+s,d=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return d&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function A3(e,t,i,s,a,o){const c=j3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function R3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let Zv=0;function Qv(e,t=.1,i=.1){return Zv++,{id:`overlay-${Date.now()}-${Zv}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function M3(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const au=.05;function Hi(e){return typeof e=="number"&&Number.isFinite(e)}function D3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const d=a?au:kr(o?1-t-au:(1-t)/2,0,1),_=c?au:kr(h?1-i-au:(1-i)/2,0,1);return{x:d,y:_}}let B3=0;function L3(e){if(!e||typeof e!="object")return null;const t=e,i=MS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Hi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Hi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Hi(t.x)&&Hi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?D3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=kr(c,0,1),h=kr(h,0,1),a=kr(a,.02,1),o=kr(o,.02,1);const d={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++B3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){d.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;d.tailAnchor=b&&Hi(b.x)&&Hi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(d.speaker=t.speaker);const _=fm(t.textStyle),x=Fu(t.bubbleStyle);return _&&(d.textStyle=_),x&&(d.bubbleStyle=x),d}function O3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&MS.includes(t.type)&&Hi(t.x)&&Hi(t.y)&&Hi(t.width)&&Hi(t.height)&&typeof t.text=="string"}function z3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=L3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),O3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function VD(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=fm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Fu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const Jv=new Set(["speech","narration"]),P3=.12;function ey(e){return Hi(e==null?void 0:e.x)&&Hi(e==null?void 0:e.y)&&Hi(e==null?void 0:e.width)&&Hi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function I3(e,t=P3){const i=[];for(let s=0;s0?d/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function Er(e){return e.kind==="text"}function H3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||Er(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function LS(e,t=E3){return!e.finalImagePath||!(e.overlays??[]).some(T3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ty,height:Math.round(ty*s/i)}}function lu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?f.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>f.jsxs("div",{className:"flex gap-2 text-xs",children:[f.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),f.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&f.jsx("div",{className:"border-l-2 border-border pl-3",children:f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&f.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function $3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),f.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&f.jsx(Rp,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&f.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[f.jsx(Rp,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),f.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:f.jsx(lu,{cut:e})})]}),!c&&p&&f.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?f.jsx(lu,{cut:e}):f.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&f.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[f.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[f.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),f.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&f.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),f.jsx(lu,{cut:e})]})]}),e.description&&f.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&f.jsx(lu,{cut:e}),s&&(()=>{const d=H3(e);return f.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":d.key,onClick:()=>s(e.id,d.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:d.label})})()]})}function F3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,d]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),d(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const y=await b.json();d(y.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{d("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:p}),f.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),f.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):f.jsx("div",{className:"h-full overflow-y-auto",children:f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>f.jsx($3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const iy=/!\[[^\]]*\]\([^)]*\)/g,q3=//g,OS=200;function W3(e){const t=(e.match(iy)||[]).length,i=e.length,s=e.replace(q3," ").replace(iy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,OS)}}function G3(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const Y3=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function K3(e){for(const t of Y3){const i=e.match(t);if(i)return i[0]}return null}function pm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=K3(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function PS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(V3(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=zS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const jf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function X3(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,d)=>p-d);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function IS(e){const t=c=>{var h;return((h=jf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...jf.map(c=>c.key),"other"],a=c=>{var h;return((h=jf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:X3(h)})}return o}const Z3=220,Af=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function mm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Af.test(x)).length,d=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=d.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Af.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):d.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Af.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function Q3(e){return/\.(webp|jpe?g)$/i.test(e)}function Mp(e){var c;let t=0,i=0,s=0,a=0,o=0;for(const h of e)Er(h)||(t++,h.cleanImagePath&&Q3(h.cleanImagePath)&&(i++,(((c=h.overlays)==null?void 0:c.length)??0)>0&&s++)),h.finalImagePath&&h.exportedAt&&a++,h.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const J3={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function ou(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function eM(e){const{cuts:t,published:i=!1}=e,s=Mp(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.needClean,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(D=>!_[D]),v=D=>s.needClean>0?ou(D,s.needClean):"no image cuts",y={plan:ou(s.total,s.total),clean:v(s.withClean),letter:v(s.withText),export:ou(s.exported,s.total),upload:ou(s.uploaded,s.total),publish:null},N=x.map((D,P)=>({key:D,label:J3[D],status:b===-1||POS,a=nM({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[f.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[f.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),f.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),f.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${sM[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[f.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&f.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&f.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&f.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[f.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),f.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),f.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Q0,{remarkPlugins:[eS,CS],rehypePlugins:[[TS,rM]],children:e})}):f.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const lM="modulepreload",oM=function(e){return"/"+e},ny={},ry=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(d){return Promise.all(d.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(d=>{if(d=oM(d),d in ny)return;ny[d]=!0;const _=d.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":lM,_||(b.as="script"),b.crossOrigin="",b.href=d,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,y)=>{b.addEventListener("load",v),b.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},gm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],cM="system-ui, sans-serif",uM=gm.find(e=>e.family==="Noto Sans"),hM=gm.find(e=>e.category==="display");function dM(e){return gm.find(i=>i.category==="body"&&i.languages.includes(e))||uM}function fM(){return hM}function pM(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function sy(e){return`"${e.family}", ${cM}`}function mM(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function vu(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function gM(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==vu(e.current)}function HS(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function kn(e,t){return e*t}function ay(e,t){return t===0?0:e/t}function ly(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=pM(e),document.head.appendChild(i)}const yu={speech:"Speech",narration:"Narration",sfx:"SFX"},xM={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Rf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:yu[e.type]}const oy=.05,_M=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function cu(e,t,i){return Math.min(i,Math.max(t,e))}function bM({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h}){var fi,ne,_e,Pe,Fe,Qe;const p=dM(c),d=fM(),_=sy(p),x=sy(d);w.useEffect(()=>{ly(p),ly(d)},[p,d]),w.useEffect(()=>{let H=!1;return ye(!1),(async()=>{try{const{ensureFontsReady:ge}=await ry(async()=>{const{ensureFontsReady:Te}=await import("./export-cut-DAQ_YjPc.js");return{ensureFontsReady:Te}},[]);await ge([p.family,d.family])}catch{}H||ye(!0)})(),()=>{H=!0}},[p.family,d.family]);const b=RS(e,t.cleanImagePath,h),v=w.useMemo(()=>z3(t.overlays),[t.overlays]),y=v.invalid.length,[N,A]=w.useState(!1),E=y===0&&v.changed&&v.overlays.length>0,[D,P]=w.useState(()=>v.overlays),[J,q]=w.useState(()=>vu(v.overlays)),L=w.useRef(null),Z=w.useCallback(H=>(ge,Te,me=400)=>{var Le;!L.current&&typeof document<"u"&&(L.current=document.createElement("canvas"));const He=(Le=L.current)==null?void 0:Le.getContext("2d");return He?(He.font=`${me} ${Te}px ${H}`,He.measureText(ge).width):ge.length*Te*.5},[]),[he,ye]=w.useState(!1),[U,re]=w.useState(null),[W,G]=w.useState(!1),[X,I]=w.useState(!1),[j,O]=w.useState(null),[B,xe]=w.useState({x:0,y:0,width:0,height:0}),T=w.useRef(null),R=w.useRef(null),Y=w.useRef(null),C=w.useCallback(()=>{const H=T.current;if(!H)return;const ge=H.clientWidth,Te=H.clientHeight;let me,He;if(t.kind==="text"){const Mt=U3(t.aspectRatio)??{width:800,height:600};me=Mt.width,He=Mt.height}else{const Mt=R.current;if(!Mt||!Mt.naturalWidth)return;me=Mt.naturalWidth,He=Mt.naturalHeight}if(!ge||!Te)return;const Le=Math.min(ge/me,Te/He),ht=me*Le,it=He*Le;xe({x:(ge-ht)/2,y:(Te-it)/2,width:ht,height:it})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=T.current;if(!H)return;const ge=new ResizeObserver(()=>C());return ge.observe(H),()=>ge.disconnect()},[C]);const se=w.useCallback(H=>{const ge=M3(H.type,H.x,H.y),Te=ge.width,me=Math.max(.08,1-H.y);if(!H.text||!he||B.width<=0)return ge;const He=H.type==="sfx"?x:_,Le=kn(Te,B.width);let ht=H.type==="sfx"?.08:.12;for(let it=0;it<24;it++){const Mt=Math.min(ht,me),Dt=kn(Mt,B.height);if(!ru(Z(He),H.text,Le,Dt,su({...H},B.height||300,Le,Dt)).overflow||Mt>=me)return{width:Te,height:Mt};ht+=.03}return{width:Te,height:Math.min(ht,me)}},[he,B,Z,_,x]),te=w.useCallback(H=>{const ge=Qv(H,.1+Math.random()*.3,.1+Math.random()*.3),Te={...ge,...se(ge)};P(me=>[...me,Te]),re(Te.id)},[se]),oe=w.useCallback(H=>{const Te={...Qv(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},me={...Te,...se(Te)};P(He=>[...He,me]),re(me.id)},[se]),$=w.useCallback((H,ge)=>{P(Te=>Te.map(me=>me.id===H?{...me,...ge}:me))},[]),ue=w.useCallback(H=>{var ht;const ge=B.height||300,Te=B.width>0?kn(H.width,B.width):200,me=B.height>0?kn(H.height,B.height):100,He=H.type==="sfx"?x:_,Le=ru(Z(He),H.text,Te,me,su({...H,textStyle:void 0},ge,Te,me));$(H.id,{textStyle:{mode:"manual",fontScale:Le.fontSize/Math.max(1,ge),fontWeight:((ht=H.textStyle)==null?void 0:ht.fontWeight)??400,lineHeightFactor:Le.fontSize>0?Le.lineHeight/Le.fontSize:1.2,speakerScale:Le.fontSize>0&&Le.speakerFontSize>0?Le.speakerFontSize/Le.fontSize:.8}})},[B,x,_,Z,$]),be=w.useCallback(H=>{P(ge=>ge.filter(Te=>Te.id!==H)),re(null),G(!1)},[]),De=w.useCallback(()=>{re(null),G(!1)},[]),Ee=w.useCallback((H,ge)=>{H.stopPropagation(),re(ge),G(!1)},[]),Be=w.useCallback((H,ge,Te)=>{H.stopPropagation(),H.preventDefault();const me=D.find(He=>He.id===ge);me&&(re(ge),Y.current={id:ge,mode:Te,startX:H.clientX,startY:H.clientY,origX:me.x,origY:me.y,origW:me.width,origH:me.height})},[D]);w.useEffect(()=>{const H=Te=>{const me=Y.current;if(!me||B.width===0)return;const He=ay(Te.clientX-me.startX,B.width),Le=ay(Te.clientY-me.startY,B.height);if(me.mode==="move"){const ht=cu(me.origX+He,0,1-me.origW),it=cu(me.origY+Le,0,1-me.origH);$(me.id,{x:ht,y:it})}else{const ht=cu(me.origW+He,oy,1-me.origX),it=cu(me.origH+Le,oy,1-me.origY);$(me.id,{width:ht,height:it})}},ge=()=>{Y.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",ge),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",ge)}},[B,$]);const je=w.useCallback(()=>{s(D)},[D,s]),Ze=w.useCallback(async()=>{if(y>0&&!N){const H=y;O(`${H} overlay${H===1?"":"s"} from the cut plan ${H===1?"has":"have"} no usable position and cannot be exported — re-place ${H===1?"it":"them"} or discard ${H===1?"it":"them"} first.`);return}I(!0),O(null);try{await s(D);const{exportCut:H,ensureFontsReady:ge}=await ry(async()=>{const{exportCut:kt,ensureFontsReady:ki}=await import("./export-cut-DAQ_YjPc.js");return{exportCut:kt,ensureFontsReady:ki}},[]),Te=D.some(kt=>kt.type==="sfx"),me=[p.family,...Te?[d.family]:[]],{ready:He,missing:Le}=await ge(me);if(!He){O(`Fonts not loaded: ${Le.join(", ")}. Check your connection and retry.`),I(!1);return}if(t.cleanImagePath&&!b.url){O(b.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),I(!1);return}const ht=b.url,it=await H(ht,D,_,x,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),Mt=new FormData,Dt=it.type==="image/webp"?"webp":"jpg";Mt.append("file",it,`cut-${t.id}.${Dt}`);const pi=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:Mt});if(pi.ok)q(vu(D)),o==null||o();else{const kt=await pi.json();O(kt.error||"Export failed")}}catch(H){O(H instanceof Error?H.message:"Export failed")}finally{I(!1)}},[t,b,D,e,i,p,d,_,x,h,s,o,y,N]),Ce=D.find(H=>H.id===U),tt=w.useMemo(()=>I3(D),[D]),pt=w.useRef(t.id);w.useEffect(()=>{pt.current!==t.id&&(pt.current=t.id,q(vu(v.overlays)))},[t.id,v.overlays]);const Ge=gM({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:J,current:D}),Ae=w.useMemo(()=>mM({...t,overlays:D},{staleExport:Ge}),[t,D,Ge]),Ve=w.useMemo(()=>HS(t),[t]),At=w.useMemo(()=>{const H={};for(const ge of D){const Te=R3(ge);let me=!1;if(he&&B.width>0&&ge.text){const He=ge.type==="sfx"?x:_,Le=kn(ge.width,B.width),ht=kn(ge.height,B.height);me=ru(Z(He),ge.text,Le,ht,su(ge,B.height||300,Le,ht)).overflow}(Te||me)&&(H[ge.id]={outOfBounds:Te,overflow:me})}return H},[D,he,B,Z,_,x]),Ot=Object.keys(At).length,ci=t.kind==="text",St=!t.cleanImagePath;return!ci&&St&&D.length===0&&!t.narration&&!((fi=t.dialogue)!=null&&fi.length)?f.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-xs font-mono text-muted",children:["Cut #",t.id]}),f.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[D.length," overlays"]}),f.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[f.jsx("button",{onClick:()=>te("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),f.jsx("button",{onClick:()=>te("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),f.jsx("button",{onClick:()=>te("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[j&&f.jsx("span",{className:"text-[10px] text-error",children:j}),f.jsx("button",{onClick:Ze,disabled:X,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:X?"Exporting...":"Export"}),f.jsx("button",{onClick:je,className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim",children:"Save"}),f.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded",children:"Close"})]})]}),y>0&&!N?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[f.jsxs("span",{children:[y," overlay",y===1?"":"s"," from the cut plan ",y===1?"has":"have"," no usable position and cannot be exported. Re-place ",y===1?"it":"them",", or"]}),f.jsxs("button",{onClick:()=>A(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",y," unplaceable overlay",y===1?"":"s"]})]}):y>0?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",y," unplaceable overlay",y===1?"":"s"," — the export will not include ",y===1?"it":"them","."]}):E?f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,tt.length>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",tt.length," bubble ",tt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",tt.map(H=>`#${H.indexA+1} ${Rf(D[H.indexA])} ↔ #${H.indexB+1} ${Rf(D[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),f.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",Ae.hasCleanImage],["script-text","Script text",Ae.hasScriptText],["bubbles",`Bubbles placed${Ae.bubblesPlaced?` (${Ae.bubblesPlaced})`:""}`,Ae.bubblesPlaced>0],["exported","Final exported",Ae.exported],["uploaded","Uploaded",Ae.uploaded]].map(([H,ge,Te])=>f.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Te?"true":"false",className:`flex items-center gap-1 ${Te?"text-green-700":"text-muted/70"}`,children:[f.jsx("span",{"aria-hidden":!0,children:Te?"✓":"○"}),ge]},H))}),Ge&&f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Ot>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[Ot," bubble",Ot===1?"":"s"," may not export cleanly:"," ",Object.entries(At).map(([H,ge])=>{const Te=D.findIndex(He=>He.id===H),me=[ge.outOfBounds?"outside image":null,ge.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Te+1} ${Rf(D[Te])} (${me})`}).join("; "),". Resize or reposition before exporting."]}),f.jsxs("div",{className:"flex-1 min-h-0 flex",children:[f.jsxs("div",{ref:T,className:"flex-1 min-w-0 relative overflow-hidden",onClick:De,"data-testid":"editor-surface",children:[t.cleanImagePath&&b.error?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!b.url?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?f.jsx("img",{ref:R,src:b.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:C}):ci?B.width>0&&f.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:B.x,top:B.y,width:B.width,height:B.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):f.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&B.width===0){const ge=H.getBoundingClientRect();ge.width>0&&xe({x:0,y:0,width:ge.width,height:ge.height})}},children:"Narration cut"}),B.width>0&&f.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:D.map(H=>{if(H.type!=="speech")return null;const ge=B.x+kn(H.x,B.width),Te=B.y+kn(H.y,B.height),me=kn(H.width,B.width),He=kn(H.height,B.height),Le=N3(H,me,He),ht=H.tailAnchor?BS(ge,Te,me,He,H.tailAnchor,Le):null,it=Math.max(1.5,B.height*.004),Mt=H.id===U;return f.jsx("path",{"data-testid":`balloon-${H.id}`,d:A3(ge,Te,me,He,ht,Le),className:`fill-white/95 ${Mt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:Mt?it+.5:it,strokeLinejoin:"round"},H.id)})}),B.width>0&&D.map(H=>{const ge=B.x+kn(H.x,B.width),Te=B.y+kn(H.y,B.height),me=kn(H.width,B.width),He=kn(H.height,B.height),Le=H.id===U,ht=H.type==="speech",it=H.type==="narration",Mt=!!At[H.id];return f.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":Mt?"true":"false",onClick:Dt=>Ee(Dt,H.id),onMouseDown:Dt=>Be(Dt,H.id,"move"),className:`absolute rounded cursor-move select-none ${ht?"":`border-2 ${xM[H.type]}`} ${it?"bg-[#f4efe6]/85 rounded-md":""} ${Le&&!ht?"ring-2 ring-accent":""} ${Mt?"ring-2 ring-amber-500":""}`,style:{left:ge,top:Te,width:me,height:He},children:[(()=>{var ki,mi;const Dt=H.type==="sfx"?x:_;if(!H.text)return f.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Dt},children:yu[H.type]});const pi=H.type!=="sfx"&&!!H.speaker;if(!he)return f.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Dt,fontSize:Math.max(9,Math.min(He*.05,16)),fontWeight:((ki=H.textStyle)==null?void 0:ki.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:pi?`${H.speaker}: ${H.text}`:H.text});const kt=ru(Z(Dt),H.text,me,He,su(H,B.height,me,He));return f.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Dt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[pi&&f.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:kt.speakerFontSize,lineHeight:1.2},children:H.speaker}),f.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:kt.fontSize,lineHeight:`${kt.lineHeight}px`,fontWeight:((mi=H.textStyle)==null?void 0:mi.fontWeight)??400},children:kt.lines.map((Gt,mn)=>f.jsx("span",{className:"block",children:Gt},mn))})]})})(),Le&&f.jsx("div",{onMouseDown:Dt=>{Dt.stopPropagation(),Be(Dt,H.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${H.id}`})]},H.id)})]}),f.jsxs("div",{className:"w-52 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[Ve.length>0&&f.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),f.jsx("div",{className:"flex flex-col gap-1",children:Ve.map(H=>f.jsxs("button",{onClick:()=>oe(H),"data-testid":`script-insert-${H.key}`,title:`Add ${H.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[f.jsxs("span",{className:"font-medium text-accent",children:["+ ",yu[H.type]]})," ",f.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Ce?f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-xs font-medium text-foreground",children:yu[Ce.type]}),Ce.speaker!==void 0&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),f.jsx("input",{value:Ce.speaker||"",onChange:H=>$(Ce.id,{speaker:H.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),f.jsx("textarea",{value:Ce.text,onChange:H=>$(Ce.id,{text:H.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),f.jsx("button",{onClick:()=>$(Ce.id,se(Ce)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((ne=Ce.textStyle)==null?void 0:ne.mode)==="manual"?f.jsx("button",{type:"button",onClick:()=>$(Ce.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):f.jsx("button",{type:"button",onClick:()=>ue(Ce),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((_e=Ce.textStyle)==null?void 0:_e.mode)==="manual"?f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),f.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Ce.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(H.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),f.jsxs("select",{value:String(Ce.textStyle.fontWeight??400),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",fontWeight:H.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[f.jsx("option",{value:"400",children:"Regular"}),f.jsx("option",{value:"700",children:"Bold"})]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),f.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Ce.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(H.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Ce.type!=="sfx"&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),f.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Ce.textStyle.speakerScale??.8).toFixed(2),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(H.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):f.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Ce.type==="speech"&&(()=>{const H=Ce.tailAnchor||{x:.5,y:1.2};return f.jsxs("div",{className:"space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),f.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:_M.map(ge=>f.jsx("button",{type:"button",onClick:()=>$(Ce.id,{tailAnchor:ge.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${ge.key}`,children:ge.label},ge.key))}),f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",f.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:ge=>$(Ce.id,{tailAnchor:{...H,x:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",f.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:ge=>$(Ce.id,{tailAnchor:{...H,y:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Ce.type!=="sfx"&&f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Pe=Ce.bubbleStyle)==null?void 0:Pe.paddingX)??.06)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Fe=Ce.bubbleStyle)==null?void 0:Fe.paddingY)??.08)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Qe=Ce.bubbleStyle)==null?void 0:Qe.cornerRadius)??.4)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(H.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),f.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font: ",Ce.type==="sfx"?d.family:p.family]}),f.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[f.jsxs("p",{children:["x: ",Ce.x.toFixed(3),", y: ",Ce.y.toFixed(3)]}),f.jsxs("p",{children:["w: ",Ce.width.toFixed(3),", h: ",Ce.height.toFixed(3)]})]}),f.jsx("button",{onClick:()=>{W?be(Ce.id):G(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:W?"Click again to delete":"Delete"})]}):f.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const vM={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},yM="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",SM="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function wM(e){var a;const t=vM[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(SM),s.push(yM),s.join(` +`).trim()}function CM(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function cy(e,t){const i=CM(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",wM(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` +`)}function kM(e,t){const i=`${t}.cuts.json`,s=HS(e),a=s.length>0?s.map(o=>o.type==="speech"?`- speech — ${o.speaker||"Speaker"}: "${o.text}"`:o.type==="narration"?`- narration: ${o.text}`:`- sfx: ${o.text}`).join(` `):"- (no dialogue/narration/SFX recorded for this cut — add a caption only if the scene needs one)";return[`Draft the speech bubbles and captions for cut ${e.id} of ${t}.`,"","Script to letter:",a,"","How to draft it:",`- Edit cut ${e.id}'s "overlays" array in ${i}: add one overlay per line above — "type":"speech" for dialogue (also set "speaker"), "narration" for captions, "sfx" for sound effects, with the line's text.`,"- Position each overlay with x, y, width, height as 0–1 fractions of the panel, roughly where it belongs over the art, and keep bubbles clear of faces.","- These are DRAFT positions only: do NOT export or upload. The writer reviews and adjusts them in the OWS lettering editor, then exports the final image there."].join(` -`)}const HS=12e3,CM=5,kM=6e4,EM=6e4,NM=5;function TM(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function jM(e,t=HS){return Math.min(t*2**e,kM)}const US=e=>new Promise(t=>setTimeout(t,e));async function AM(e,t={}){var c;const i=t.sleep??US,s=t.maxRetries??CM,a=t.baseDelayMs??HS;let o=0;for(;;){const h=await e();if(h.ok||!TM(h.status,h.errorMessage)||o>=s)return h;const p=jM(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function RM(e={}){const t=e.limit??NM,i=e.windowMs??EM,s=e.sleep??US,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const d=o[0]+i-a();d>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:d}),await s(d)),c()}o.push(a())}}const Dp=1024*1024;function cy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function MM(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await cy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Dp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await cy(e,"image/jpeg",s);if(a.size<=Dp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const DM=["image/webp","image/jpeg"];function $S(e){return DM.includes(e.type)&&e.size<=Dp}async function BM(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function qu(e){if($S(e))return e;const t=await BM(e);return MM(t)}function LM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function OM(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter(LM):[]}async function zM(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function PM(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function IM(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function HM(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function UM({image:e,authFetch:t}){const i=PM(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?f.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):f.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function $M({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[x,_]=w.useState("");w.useEffect(()=>{let N=!1;return(async()=>{const L=await OM(e);N||o(L)})(),()=>{N=!0}},[e]);const b=x.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(N=>N.name.toLowerCase().includes(b)):a:[],[a,b]),y=Date.now(),E=async N=>{h(null),d(N.token);try{const L=await zM(e,N);await i(L)}catch(L){h(L instanceof Error?L.message:"Could not import the generated image")}finally{d(null)}},A=a!==null&&a.length>0;return f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),f.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),A&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"search",value:x,onChange:N=>_(N.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),f.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),A&&v.length===0&&f.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",x.trim(),"”."]}),A&&v.length>0&&f.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(N=>f.jsxs("li",{"data-testid":`codex-image-${N.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[f.jsx(UM,{image:N,authFetch:e}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("p",{className:"text-[11px] text-foreground",children:[HM(N.mtimeMs,y)," · ",IM(N.size)]}),f.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:N.name,children:N.name})]}),f.jsx("button",{onClick:()=>E(N),disabled:p!==null,"data-testid":`codex-import-${N.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===N.token?"Importing…":"Import to this cut"})]},N.token))}),c&&f.jsx("p",{className:"text-[11px] text-error",children:c})]})}const FM={done:"✓",current:"▸",todo:"○"};function qM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=PS(t),d=((E=e.steps.find(A=>A.key==="upload"))==null?void 0:E.status)==="done",x=d&&c&&!h,_=h||c?"done":d?"current":"todo",b=h?"done":x?"current":"todo",v=[...e.steps.filter(A=>A.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:_,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],y=s?a||"Finishing…":h?"Published ✓":x?"Episode ready to publish":"Finish episode";return f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/50 space-y-2 flex-shrink-0","data-testid":"finish-episode-panel",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&f.jsxs("span",{className:"text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]})]}),f.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(A=>f.jsxs("li",{"data-testid":`finish-step-${A.key}`,"data-status":A.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${A.status==="current"?"border-accent/40 bg-accent/10 text-accent":A.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[f.jsx("span",{"aria-hidden":!0,children:FM[A.status]}),f.jsx("span",{children:A.label}),A.detail&&f.jsxs("span",{className:"text-muted",children:["· ",A.detail]})]},A.key))}),f.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-3 py-1 text-xs border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:y}),p.length>0&&f.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(A=>f.jsxs("div",{"data-testid":`finish-issue-group-${A.key}`,className:"text-[10px]",children:[f.jsx("p",{className:"font-medium text-amber-700",children:A.title}),f.jsx("ul",{className:"ml-3 list-disc text-muted",children:A.lines.map((N,L)=>f.jsx("li",{children:N},L))})]},A.key))})]})}function WM(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function FS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":kr(e)?"text":"missing"}const GM={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},YM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function KM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:kr(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function VM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:d,syncing:x,staleMessages:_,onRepairStale:b,repairing:v,conversionPng:y,onConvert:E,converting:A,rowRef:N}){var De;const L=w.useRef(null),[O,J]=w.useState(!1),[$,M]=w.useState(null),[X,he]=w.useState(!1),[ye,U]=w.useState(!1),[se,W]=w.useState(!1),[G,Z]=w.useState(!1),[I,j]=w.useState("manual"),[z,B]=w.useState(!1),_e=FS(e),T=_.length>0,R=!!y,Y=w.useCallback(async()=>{y&&(Z(!0),await E(e.id,y),Z(!1),c())},[y,E,e.id,c]),C=w.useCallback(async Ee=>{J(!0),M(null);try{let Be=Ee;if(!$S(Ee))try{Be=await qu(Ee)}catch(tt){return M(tt instanceof Error?tt.message:"Could not import image"),!1}const je=Be.type==="image/jpeg"?"jpg":"webp",Ze=new FormData;Ze.append("file",new File([Be],`clean.${je}`,{type:Be.type}));const we=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ze});if(!we.ok){const tt=await we.json();return M(tt.error||"Upload failed"),!1}return c(),!0}catch{return M("Upload failed"),!1}finally{J(!1)}},[o,t,i,e.id,c]),ae=KM(e,R,T),ie=e.cleanImagePath??y??null,oe=((De=e.overlays)==null?void 0:De.length)??0,F=!kr(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!T&&!R,ue=w.useCallback(()=>{var Ee;(Ee=navigator.clipboard)==null||Ee.writeText(wM(e,i)),B(!0),setTimeout(()=>B(!1),2e3)},[e,i]),be=ae.key==="convert"?{label:G?"Converting…":"Convert image",onClick:Y,testid:`card-convert-${e.id}`}:ae.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:ae.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:ae.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null;return f.jsxs("div",{ref:N,"data-cut-row":e.id,className:`border rounded ${s?"border-accent/30":"border-border"}`,children:[f.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[f.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[f.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${YM[ae.tone]}`}),f.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),f.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${GM[ae.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:ae.label})]}),ie?f.jsx(Rp,{storyName:t,assetPath:ie,authFetch:o,alt:`Cut ${e.id} artwork`,className:"w-full max-h-44 object-contain rounded border border-border bg-white"}):f.jsx("div",{className:"w-full h-20 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:kr(e)?"Text panel — no artwork needed":"No artwork yet"}),f.jsx("button",{onClick:a,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),F&&f.jsxs("div",{className:"space-y-1","data-testid":`lettering-${e.id}`,children:[f.jsx("div",{className:"text-[10px] font-medium text-muted uppercase tracking-wider",children:"Lettering"}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="manual",onChange:()=>j("manual"),"data-testid":`lettering-mode-manual-${e.id}`}),"Manual — I place bubbles myself"]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="ai",onChange:()=>j("ai"),"data-testid":`lettering-mode-ai-${e.id}`}),"AI draft — ask the agent to place initial bubbles"]}),I==="ai"&&f.jsx("p",{className:"text-[10px] text-muted",children:"Paste it to your agent, then review the draft bubbles here and export the final cut."})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[F?I==="manual"?f.jsx("button",{onClick:h,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:oe>0?"Review lettering":"Add speech bubbles"}):f.jsx("button",{onClick:ue,"data-testid":`copy-lettering-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded border border-accent/40 text-accent hover:bg-accent/5",children:z?"Copied!":"Copy AI lettering prompt"}):be?f.jsx("button",{onClick:be.onClick,disabled:ae.key==="convert"&&(G||A),"data-testid":be.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:be.label}):null,f.jsx("button",{onClick:a,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:s?"Hide details":"Open details"})]})]}),s&&f.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[R&&f.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[f.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),f.jsx("button",{onClick:Y,disabled:G||A,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:G?"Converting…":"Convert image"})]}),T&&!R&&f.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[_.map((Ee,Be)=>f.jsx("p",{className:"text-[11px] text-error",children:Ee},Be)),f.jsx("button",{onClick:b,disabled:v,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:v?"Repairing…":"Clear stale path"})]}),!kr(e)&&f.jsxs("div",{className:"mt-2 space-y-2",children:[f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(oy(e,i)),he(!0),setTimeout(()=>he(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:X?"Copied!":"Copy Codex task"}),f.jsx("input",{ref:L,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ee=>{var je;const Be=(je=Ee.target.files)==null?void 0:je[0];Be&&C(Be),Ee.target.value=""}}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("button",{onClick:()=>{var Ee;return(Ee=L.current)==null?void 0:Ee.click()},disabled:O,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:O?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),f.jsx("button",{onClick:()=>W(Ee=>!Ee),disabled:O,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:se?"Hide Codex images":"Import from Codex"})]}),se&&f.jsx($M,{authFetch:o,cutId:e.id,onImport:async Ee=>{await C(Ee)&&W(!1)},onClose:()=>W(!1)}),!e.cleanImagePath&&f.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),_e==="missing"&&f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),f.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",f.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(oy(e,i)),U(!0),setTimeout(()=>U(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:ye?"Copied!":"Copy Codex task"})]}),_e==="missing"&&p&&f.jsx("button",{onClick:d,disabled:x,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:x?"Syncing...":"Found local clean image — sync to cut plan"}),$&&f.jsx("p",{className:"text-xs text-error mt-1",children:$})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||kr(e))&&f.jsx("button",{onClick:h,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&f.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&f.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ee,Be)=>f.jsxs("p",{children:[f.jsxs("span",{className:"font-medium",children:[Ee.speaker,":"]})," ",Ee.text]},Be))}),e.narration&&f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function uy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h}){var Gt,fn;const[p,d]=w.useState(null),x=w.useRef(o);x.current=o;const _=w.useRef(h);_.current=h;const[b,v]=w.useState(!0),[y,E]=w.useState(null),[A,N]=w.useState(null),[L,O]=w.useState(null),[J,$]=w.useState(!1),[M,X]=w.useState([]),[he,ye]=w.useState(!1),[U,se]=w.useState(""),[W,G]=w.useState({markdownReady:!1,published:!1}),[Z,I]=w.useState(!1),[j,z]=w.useState(!1),[B,_e]=w.useState(!1),[T,R]=w.useState(null),[Y,C]=w.useState(null),[ae,ie]=w.useState(new Set),[oe,F]=w.useState(new Map),[ue,be]=w.useState(!1),[De,Ee]=w.useState(null),[Be,je]=w.useState(!1),[Ze,we]=w.useState(null),tt=w.useRef(new Map),mt=w.useRef(null),Ge=t.replace(/\.md$/,"");w.useEffect(()=>{var de;c&&mt.current!==c.seq&&(mt.current=c.seq,c.openEditor?O(c.cutId):(N(c.cutId),we(c.cutId)),(de=_.current)==null||de.call(_))},[c]),w.useEffect(()=>{var Re;if(Ze==null)return;const de=tt.current.get(Ze);de&&((Re=de.scrollIntoView)==null||Re.call(de,{behavior:"smooth",block:"center"}),we(null))},[Ze,p]);const Ae=w.useCallback(async()=>{var de;try{const Re=await i(`/api/stories/${e}/cuts/${Ge}`);if(Re.status===404){d(null);return}if(!Re.ok){const st=await Re.json();E(st.error||"Failed to load cuts");return}const We=await Re.json();d(We),E(null);try{const st=await i(`/api/stories/${e}/${t}`);if(st.ok){const nt=await st.json(),te=typeof(nt==null?void 0:nt.content)=="string"?nt.content:"",Ce=Array.isArray(We==null?void 0:We.cuts)?We.cuts:[],Le=te.length>0&&OS(te,Ce).ready,ft=(nt==null?void 0:nt.status)==="published"||(nt==null?void 0:nt.status)==="published-not-indexed";G({markdownReady:Le,published:ft})}else G({markdownReady:!1,published:!1})}catch{G({markdownReady:!1,published:!1})}(de=x.current)==null||de.call(x)}catch{E("Failed to load cuts")}finally{v(!1)}},[i,e,Ge,t]),Ve=w.useCallback(async()=>{be(!1);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/detect-clean-images`);if(!de.ok)return;const Re=await de.json();ie(new Set(Array.isArray(Re.detected)?Re.detected:[]));const We=new Map,st=Re.stale;if(Array.isArray(st))for(const nt of st){if(typeof(nt==null?void 0:nt.cutId)!="number"||typeof(nt==null?void 0:nt.message)!="string")continue;const te=We.get(nt.cutId)??[];te.push(nt.message),We.set(nt.cutId,te)}F(We),be(!0)}catch{}},[i,e,Ge]),Mt=w.useCallback(async()=>{Ee(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/asset-diagnostics`);if(!de.ok)return;const Re=await de.json();Ee(Array.isArray(Re.diagnostics)?Re.diagnostics:null)}catch{}},[i,e,Ge]),zt=w.useCallback(async()=>{je(!0);try{await Promise.all([Ae(),Ve(),Mt()])}finally{je(!1)}},[Ae,Ve,Mt]),ai=w.useCallback(async()=>{I(!0),C(null),X([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/sync-clean-images`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Sync failed");else{const We=Array.isArray(Re.synced)?Re.synced.length:0,st=Array.isArray(Re.cleared)?Re.cleared.length:0,nt=Array.isArray(Re.rejected)?Re.rejected:[];nt.length>0&&X(nt.map(Ce=>`Cut ${Ce.cutId}: ${Ce.reason}`));const te=[];We>0&&te.push(`Synced ${We}`),st>0&&te.push(`Cleared ${st} stale path${st===1?"":"s"}`),C(te.length>0?te.join(", "):"No new clean images"),await Ae(),await Ve(),await Mt()}}catch{C("Sync failed")}I(!1)},[i,e,Ge,Ae,Ve,Mt]),wt=w.useCallback(async(de,Re)=>{try{const We=await i(jS(e,Re));if(!We.ok)return!1;const st=await We.blob(),nt=await qu(new File([st],"clean.png",{type:st.type||"image/png"})),te=nt.type==="image/jpeg"?"jpg":"webp",Ce=new FormData;return Ce.append("file",new File([nt],`clean.${te}`,{type:nt.type})),(await i(`/api/stories/${e}/cuts/${Ge}/upload-clean/${de}`,{method:"POST",body:Ce})).ok}catch{return!1}},[i,e,Ge]),hi=w.useCallback(async de=>{_e(!0),R(null);let Re=0;const We=[];for(const st of de)await wt(st.cutId,st.pngPath)?Re++:We.push(st.cutId);await zt(),_e(!1),R(We.length===0?`Converted ${Re} image${Re===1?"":"s"} to WebP`:`Converted ${Re}; ${We.length} failed (Cut ${We.join(", ")}) — try Convert image on each`)},[wt,zt]),re=w.useCallback(async()=>{var nt;if(!p)return;ye(!0),se(""),X([]);const de=p.cuts.filter(te=>te.finalImagePath&&!te.uploadedCid),Re=[],We=RM({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:te})=>se(`Upload limit reached — waiting ${Math.round(te/1e3)}s before continuing…`)});for(let te=0;te{const Et=await i("/api/publish/upload-plot-image",{method:"POST",body:pt});if(Et.ok){const{cid:pi,url:fr}=await Et.json();return{ok:!0,status:Et.status,cid:pi,url:fr}}const $t=await Et.json().catch(()=>({}));return{ok:!1,status:Et.status,errorMessage:$t.error}},{...a,onWaiting:({attempt:Et,maxRetries:$t,waitMs:pi})=>se(`Cut ${Ce.id} rate-limited — waiting ${Math.round(pi/1e3)}s before retry ${Et}/${$t}...`)});if(!Tt.ok){Re.push(`Cut ${Ce.id}: upload failed — ${Tt.errorMessage||"unknown"}`);continue}const{cid:Je,url:ot}=Tt;(await i(`/api/stories/${e}/cuts/${Ge}/set-uploaded/${Ce.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Je,url:ot})})).ok||Re.push(`Cut ${Ce.id}: failed to record upload`)}catch(Le){Re.push(`Cut ${Ce.id}: ${Le instanceof Error?Le.message:"failed"}`)}}if(Re.length>0){X(Re),ye(!1),se(""),Ae();return}se("Preparing episode for publishing…");const st=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(st.ok){const te=await st.json();((nt=te.warnings)==null?void 0:nt.length)>0&&X(te.warnings)}ye(!1),se(""),Ae()},[p,i,e,Ge,a,Ae]),xe=w.useCallback(async()=>{z(!0),C(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/repair-asset-paths`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Repair failed");else{const We=Array.isArray(Re.cleared)?Re.cleared.length:0;C(We>0?`Cleared ${We} stale path${We===1?"":"s"}`:"No stale paths to clear"),await Ae(),await Ve()}}catch{C("Repair failed")}z(!1)},[i,e,Ge,Ae,Ve]),[Pe,Fe]=w.useState(!1),Qe=w.useCallback(async()=>{if(p){Fe(!0);try{const de=p.cuts.reduce((nt,te)=>Math.max(nt,te.id),0)+1,Re={id:de,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},We={...p,cuts:[...p.cuts,Re]},st=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(We)});if(st.ok)N(de),await Ae();else{const nt=await st.json().catch(()=>({}));C(nt.error||"Could not add text panel")}}catch{C("Could not add text panel")}Fe(!1)}},[p,i,e,Ge,Ae]);if(w.useEffect(()=>{Ae(),Ve(),Mt()},[Ae,Ve,Mt]),b)return f.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(y)return f.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:y}),f.jsxs("p",{className:"text-xs text-muted",children:[Ge,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),f.jsx("button",{onClick:Ae,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!p||p.cuts.length===0)return f.jsxs("div",{className:"p-4 text-center space-y-1",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const H=L!==null?p.cuts.find(de=>de.id===L):null;if(H)return f.jsx(_M,{storyName:e,cut:H,plotFile:Ge,language:s,authFetch:i,onSave:async de=>{const Re={...p,cuts:p.cuts.map(st=>st.id===L?{...st,overlays:de}:st)},We=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Re)});if(!We.ok){const st=await We.json().catch(()=>({}));throw new Error(st.error||"Failed to save overlays")}},onExported:()=>Ae(),onClose:()=>{O(null),Ae()}});const ge=p.cuts.reduce((de,Re)=>{const We=FS(Re);return de[We]++,de},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),Te=p.cuts.filter(de=>!kr(de)).length,me=p.cuts.filter(de=>BS(de)).map(de=>de.id),He=Q3({cuts:p.cuts,published:W.published}),Oe=((Gt=He.steps.find(de=>de.key==="upload"))==null?void 0:Gt.status)==="done",ut=p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)||Oe&&!W.markdownReady,it=(De??[]).filter(de=>de.state==="needs-conversion"&&de.convertiblePng).map(de=>({cutId:de.cutId,pngPath:de.convertiblePng})),Dt=new Map(it.map(de=>[de.cutId,de.pngPath])),Bt=(De??[]).filter(de=>de.state==="needs-conversion"&&de.issue).map(de=>de.issue),di=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((fn=Ge.match(/\d+/))==null?void 0:fn[0])??"0",10)+1}`,kt=typeof p.title=="string"?p.title:null,Ci=p.cuts.filter(de=>!kr(de)),fi={cuts:p.cuts.length,artwork:Ci.filter(de=>de.cleanImagePath||Dt.has(de.id)).length,converted:Ci.filter(de=>de.cleanImagePath&&/\.(webp|jpe?g)$/i.test(de.cleanImagePath)).length,lettered:p.cuts.filter(de=>{var Re;return(((Re=de.overlays)==null?void 0:Re.length)??0)>0||!!de.finalImagePath}).length,uploaded:p.cuts.filter(de=>de.uploadedCid||de.uploadedUrl).length};return f.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[f.jsxs("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"font-serif text-foreground truncate",children:di}),kt&&f.jsxs("span",{className:"text-muted truncate",children:["· ",kt]})]}),f.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[fi.cuts," cuts · ",fi.artwork," artwork found · ",fi.converted," converted · ",fi.lettered," lettered · ",fi.uploaded," uploaded"]})]}),f.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[f.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),f.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[f.jsxs("span",{className:"font-mono text-muted",children:[p.cuts.length," cuts"]}),ge.missing>0&&f.jsxs("span",{className:"text-muted",children:[ge.missing," missing"]}),ge.clean>0&&f.jsxs("span",{className:"text-green-700",children:[ge.clean," clean"]}),ge.lettered>0&&f.jsxs("span",{className:"text-amber-700",children:[ge.lettered," lettered"]}),ge.uploaded>0&&f.jsxs("span",{className:"text-green-700",children:[ge.uploaded," uploaded"]}),ge.text>0&&f.jsxs("span",{className:"text-accent",children:[ge.text," text ",ge.text===1?"panel":"panels"]}),f.jsx("button",{onClick:async()=>{$(!0),X([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(de.ok){const Re=await de.json();X(Re.warnings||[])}}catch{}$(!1)},disabled:J,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:J?"Preparing…":"Prepare episode for publish"}),f.jsx("button",{onClick:Qe,disabled:Pe,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:Pe?"Adding…":"Add narration/text panel"}),f.jsx("button",{onClick:zt,disabled:Be,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:Be?"Checking…":"Refresh assets"}),f.jsx("button",{onClick:ai,disabled:Z,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:Z?"Syncing...":"Sync clean images"}),f.jsx("button",{onClick:re,disabled:he||!(p!=null&&p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:U||"Upload & Prepare for Publish"})]})]}),f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",f.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," for a narration or title card. It becomes a solid card exported as a final image."]})]}),me.length>0&&f.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[me.length===1?"Cut":"Cuts"," ",me.join(", ")," ",me.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export ",me.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),ue&&Te>0&&ge.missing===0&&oe.size===0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[f.jsx("span",{"aria-hidden":!0,children:"✓"}),f.jsxs("span",{children:["All ",Te," clean image",Te===1?"":"s"," present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),Y&&f.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:Y}),it.length>0&&f.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[it.length," PNG image",it.length===1?"":"s"," found"]}),f.jsx("button",{onClick:()=>hi(it),disabled:B,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:B?"Converting…":"Convert all to WebP"})]}),f.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),T&&f.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:T}),Bt.length>0&&f.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[f.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Bt.map((de,Re)=>f.jsx("li",{children:de},Re))})]})]}),De&&De.length>0&&(()=>{const de=WM(De),Re=De.filter(We=>We.state==="missing");return f.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[f.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",de.uploaded," uploaded · ",de.finalReady," final · ",de.cleanReady," clean · ",de.planned," planned",de.needsConversion>0?` · ${de.needsConversion} needs conversion`:"",de.missing>0?` · ${de.missing} missing`:""]}),Re.length>0&&f.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:Re.map(We=>f.jsx("li",{children:We.issue},We.cutId))})]})})(),f.jsx(qM,{checklist:He,issues:M,onFinish:re,finishing:he,progressText:U,canFinish:ut,markdownReady:W.markdownReady,published:W.published}),f.jsx("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-2","data-testid":"cut-list-scroll",children:p.cuts.map(de=>f.jsx(VM,{cut:de,storyName:e,plotFile:Ge,expanded:A===de.id,onToggle:()=>N(A===de.id?null:de.id),authFetch:i,onUpdated:()=>{Ae(),Ve(),Mt()},onOpenEditor:()=>O(de.id),detectedLocalClean:ae.has(de.id),onSyncClean:ai,syncing:Z,staleMessages:oe.get(de.id)??[],onRepairStale:xe,repairing:j,conversionPng:Dt.get(de.id)??null,onConvert:wt,converting:B,rowRef:Re=>{Re?tt.current.set(de.id,Re):tt.current.delete(de.id)}},de.id))})]})}function qS({coach:e,onAction:t,className:i=""}){const[s,a]=w.useState(null),o=s!==null&&s===(e==null?void 0:e.prompt);return e?f.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 bg-accent/5 border-b border-accent/30 text-xs ${i}`,"data-testid":"workflow-coach","data-stage":e.stageLabel,"data-action-kind":e.actionKind,"data-ui-action":e.uiAction??"",children:[f.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-accent flex-shrink-0","data-testid":"workflow-coach-stage",children:e.stageLabel}),f.jsxs("span",{className:"min-w-0 flex-1 text-foreground","data-testid":"workflow-coach-action",children:[f.jsx("span",{className:"text-muted",children:"Next: "}),f.jsx("span",{className:"font-medium",children:e.action})]}),e.actionKind==="agent"&&e.prompt?f.jsx("button",{onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>a(c)).catch(()=>{})},"data-testid":"workflow-coach-copy",className:"flex-shrink-0 rounded bg-accent px-2.5 py-1 text-[11px] font-medium text-white hover:bg-accent-dim transition-colors",children:o?"Copied!":"Copy prompt"}):e.actionKind==="ui"&&e.uiAction?f.jsx("button",{onClick:()=>t(e.uiAction,e.episodeFile),"data-testid":"workflow-coach-do",className:"flex-shrink-0 rounded bg-accent px-2.5 py-1 text-[11px] font-medium text-white hover:bg-accent-dim transition-colors",children:e.action}):null]}):null}function XM({storyName:e,fileName:t,authFetch:i,refreshKey:s=0,onAction:a}){const[o,c]=w.useState(null),h=JSON.stringify([e,t??"",s]),[p,d]=w.useState(null);return p!==h&&(c(null),d(h)),w.useEffect(()=>{let x=!1;const _=t?`?focus=${encodeURIComponent(t)}`:"";return i(`/api/stories/${e}/progress${_}`).then(b=>b.ok?b.json():null).then(b=>{x||c((b==null?void 0:b.coach)??null)}).catch(()=>{}),()=>{x=!0}},[e,t,i,s]),f.jsx(qS,{coach:o,onAction:a})}const ZM=1024*1024,QM=["image/webp","image/jpeg"],JM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function eD(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function hy(e){return e.size>ZM?"Image exceeds 1MB limit":QM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function tD(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Bp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function iD(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function jo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function nD(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Lp(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function _m(e){var s;const t=Bp(e.fileContent);if(t)return!Lp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Lp(i)}function xm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Bp(i);if(t==="genesis.md"){const p=a?Bp(a):null;return(h??p??iD(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),d=nD(t);return((p||d)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function rD(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function sD(e){return rD(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function dy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function aD(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Mf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Df(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function lD(e){return!!e&&e.ready===!1}function oD(e){const t=Df(e.requiredBalance)??Df(e.creationFee),i=Df(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const cD={...ol,attributes:{...ol.attributes,img:["src","alt","title"]}},uD="https://ipfs.filebase.io/ipfs/";function hD(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function dD(e){const t=hD(e),i=[];for(const a of t)a.url.startsWith(uD)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function fD({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:d,hasGenesis:x=!1,onViewProgress:_,onOpenFile:b,onViewPublish:v}){const[y,E]=w.useState(null),[A,N]=w.useState(!1),[L,O]=w.useState("preview"),[J,$]=w.useState("publish"),[M,X]=w.useState("text"),[he,ye]=w.useState(null),U=w.useCallback((ee,Se)=>{O("edit"),ye(Ne=>({cutId:ee,openEditor:Se,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[se,W]=w.useState(""),[G,Z]=w.useState(!1),[I,j]=w.useState(!1),[z,B]=w.useState(!1),[_e,T]=w.useState(null),[R,Y]=w.useState(""),[C,ae]=w.useState(""),[ie,oe]=w.useState(!1),[F,ue]=w.useState(null),[be,De]=w.useState(0),[Ee,Be]=w.useState(0),[je,Ze]=w.useState(null),[we,tt]=w.useState(null),[mt,Ge]=w.useState(null),[Ae,Ve]=w.useState(0),Mt=w.useRef(null),zt=w.useRef(!1),[ai,wt]=w.useState(!1),[hi,re]=w.useState(rl[0]),[xe,Pe]=w.useState(Xr[0]),[Fe,Qe]=w.useState(!1),[H,ge]=w.useState(null),[Te,me]=w.useState(null),[He,Oe]=w.useState(!1),[ut,it]=w.useState(!1),[Dt,Bt]=w.useState(!1),[di,kt]=w.useState(null),[Ci,fi]=w.useState(!1),Gt=w.useRef(null),fn=w.useRef(null),[de,Re]=w.useState(!1),[We,st]=w.useState(null),[nt,te]=w.useState(null),[Ce,Le]=w.useState("unknown"),ft=w.useRef(!1),[bt,pt]=w.useState(!1),[Tt,Je]=w.useState(!1),[ot,Xe]=w.useState(null),[Et,$t]=w.useState([]),[pi,fr]=w.useState(null),pn=w.useRef(null),jr=w.useRef(null),mi=w.useCallback(async()=>{if(!e||!t){E(null);return}const ee=`${e}/${t}`,Se=jr.current!==ee;Se&&(jr.current=ee);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Ke=await Ne.json();E(Ke),(Se||!zt.current)&&(W(Ke.content??""),Se&&(j(!1),zt.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{N(!0),mi().finally(()=>N(!1))},[mi]),w.useEffect(()=>{if(!e||!t||L==="edit"&&I)return;const ee=setInterval(mi,3e3);return()=>clearInterval(ee)},[e,t,mi,L,I]);const[li,Pn]=w.useState(null),nr=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!nr||!e){Pn(null);return}let ee=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||Pn(Se?Mp(Se.cuts||[]):null)}).catch(()=>{ee||Pn(null)}),()=>{ee=!0}},[nr,e,i]);const ct=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!ct||!e||!t){ue(null),De(0),Be(0),Ze(null);return}let ee=!1;const Se=t.replace(/\.md$/,"");return Ze(null),(async()=>{try{const[Ne,Ke]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Se}`)]);if(ee)return;if(!Ke.ok){ue("error"),De(0),Be(0),Ze(null);return}const Nt=await Ke.json(),gi=Nt.cuts||[],En=Ne.ok?(await Ne.json()).content??"":"",an=zS(En,gi);ee||(ue(an.stage),De(an.awaitingCount),Be(an.totalCuts),Ze(Mp(gi)),Ge(typeof Nt.title=="string"?Nt.title:null))}catch{ee||(ue("error"),De(0),Be(0),Ze(null))}})(),()=>{ee=!0}},[ct,e,t,i,y==null?void 0:y.content,y==null?void 0:y.status,Ae]),w.useEffect(()=>{if(!e){tt(null);return}let ee=!1;return i(`/api/stories/${e}/structure.md`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||tt((Se==null?void 0:Se.content)??null)}).catch(()=>{}),()=>{ee=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ee=bu(p);let Se=ee??"";if(!ee&&we){const Ke=we.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Ke&&(Se=bu(Ke[1].replace(/\*+/g,"").trim())??"")}Y(Se);let Ne=h&&Xr.find(Ke=>Ke.toLowerCase()===h.toLowerCase())||"";if(!Ne&&we){const Ke=we.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Ke&&(Ne=Xr.find(Nt=>Nt.toLowerCase()===Ke[1].replace(/\*+/g,"").trim().toLowerCase())||"")}ae(Ne),oe(d??!1)},[e,p,h,d,we]);const In=w.useCallback(ee=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}).catch(()=>{})},[e,i]),rr=w.useCallback(async()=>{if(!(!e||!t)){Z(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:se})})).ok&&(j(!1),zt.current=!1,E(Se=>Se&&{...Se,content:se}))}catch{}Z(!1)}},[e,t,i,se]),tn=w.useCallback(async()=>{if(!e||!t)return;const ee=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ee}/generate-markdown`,{method:"POST"})).ok&&(await mi(),Ve(Ne=>Ne+1))}catch{}},[e,t,i,mi]),Hn=w.useCallback((ee,Se)=>{if(ee==="view-progress"){_==null||_();return}if(Se&&Se!==t){b==null||b(Se);return}switch(ee){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":O("edit"),X("cuts");break;case"generate-markdown":tn();break;case"publish":O("preview");break}},[t,_,b,tn]),Xt=w.useCallback(ee=>{var Ke;const Se=(Ke=ee.target.files)==null?void 0:Ke[0];if(!Se)return;ft.current=!0,st(null),te(null);const Ne=hy(Se);if(Ne){ge(null),me(Nt=>(Nt&&URL.revokeObjectURL(Nt),null)),Gt.current&&(Gt.current.value=""),kt(Ne),Le("invalid");return}ge(Se),me(Nt=>(Nt&&URL.revokeObjectURL(Nt),URL.createObjectURL(Se))),kt(null),Le("selected")},[]),Un=w.useCallback(async ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];if(fn.current&&(fn.current.value=""),!(!Se||!e)){ft.current=!0,st(null),Re(!0),kt(null);try{let Ke;try{Ke=await qu(Se)}catch(lr){ge(null),me(Ls=>(Ls&&URL.revokeObjectURL(Ls),null)),kt(lr instanceof Error?lr.message:"Could not import image");return}const Nt=Ke.type==="image/jpeg"?"jpg":"webp",gi=new File([Ke],`cover.${Nt}`,{type:Ke.type}),En=new FormData;En.append("file",gi);const an=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:En});if(!an.ok){const lr=await an.json().catch(()=>({}));kt(lr.error||"Cover import failed");return}ge(gi),me(lr=>(lr&&URL.revokeObjectURL(lr),URL.createObjectURL(gi))),te(null),Le("selected"),kt(null)}catch{kt("Cover import failed")}finally{Re(!1)}}},[e,i]),ts=w.useCallback(async ee=>{if(ee.size>1024*1024){Xe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ee.type)){Xe("Only WebP and JPEG images are accepted");return}Je(!0),Xe(null);try{const Ne=new FormData;Ne.append("file",ee);const Ke=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Ke.ok){const gi=await Ke.json();throw new Error(gi.error||"Upload failed")}const Nt=await Ke.json();$t(gi=>[...gi,{cid:Nt.cid,url:Nt.url}])}catch(Ne){Xe(Ne instanceof Error?Ne.message:"Upload failed")}finally{Je(!1),pn.current&&(pn.current.value="")}},[i]),ha=w.useCallback(ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];Se&&ts(Se)},[ts]),pr=w.useCallback(async()=>{if(y!=null&&y.storylineId){Oe(!0),kt(null),fi(!1);try{let ee;if(H){const Ne=new FormData;Ne.append("file",H);const Ke=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Ke.ok){const gi=await Ke.json();throw new Error(gi.error||"Cover upload failed")}ee=(await Ke.json()).cid}const Se=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:y.storylineId,...ee!==void 0&&{coverCid:ee},genre:hi,language:xe,isNsfw:Fe})});if(!Se.ok){const Ne=await Se.json();throw new Error(Ne.error||"Update failed")}fi(!0),ge(null),ee!==void 0&&(Bt(!0),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Le("unknown"),Gt.current&&(Gt.current.value="")),setTimeout(()=>fi(!1),3e3)}catch(ee){kt(ee instanceof Error?ee.message:"Update failed")}finally{Oe(!1)}}},[y==null?void 0:y.storylineId,H,hi,xe,Fe,i]);w.useEffect(()=>{wt(!1),ge(null),me(null),kt(null),fi(!1),it(!1),pt(!1),$t([]),Xe(null),st(null),te(null),Le("unknown"),ft.current=!1,X("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!y||y.storylineId||y.status==="published"||y.status==="published-not-indexed"||ft.current)return;let ee=!1;return(async()=>{try{const Se=await i(`/api/stories/${e}/cover-asset`);if(ee||!Se.ok)return;const Ne=await Se.json();if(ee)return;if(!(Ne!=null&&Ne.found)){Le("none");return}if(!Ne.valid){te(Ne.error||"Detected cover asset is invalid and was not used"),Le("invalid");return}const Ke=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ee||!Ke.ok)return;const Nt=await Ke.blob(),gi=new File([Nt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(hy(gi)||ee||ft.current)return;ge(gi),me(En=>(En&&URL.revokeObjectURL(En),URL.createObjectURL(gi))),st(Ne.path),Le("detected")}catch{}})(),()=>{ee=!0}},[e,t,y,y==null?void 0:y.status,y==null?void 0:y.storylineId,i]),w.useEffect(()=>{if(!ai||!(y!=null&&y.storylineId))return;it(!1);const ee="https://plotlink.xyz";let Se=!1;return fetch(`${ee}/api/storyline/${y.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!Se){if(!Ne){kt("Could not load current story metadata");return}if(Ne.genre){const Ke=bu(Ne.genre);Ke&&re(Ke)}if(Ne.language){const Ke=Xr.find(Nt=>Nt.toLowerCase()===Ne.language.toLowerCase());Ke&&Pe(Ke)}Ne.isNsfw!==void 0&&Qe(!!Ne.isNsfw),Bt(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),it(!0)}}).catch(()=>{Se||kt("Could not load current story metadata")}),()=>{Se=!0}},[ai,y==null?void 0:y.storylineId]),w.useEffect(()=>{if(L!=="edit")return;const ee=Se=>{(Se.metaKey||Se.ctrlKey)&&Se.key==="s"&&(Se.preventDefault(),rr())};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[L,rr]),w.useEffect(()=>{if((y==null?void 0:y.status)!=="published-not-indexed"||!y.publishedAt)return;const ee=new Date(y.publishedAt).getTime(),Se=300*1e3,Ne=()=>{const Nt=Math.max(0,Se-(Date.now()-ee));T(Nt)};Ne();const Ke=setInterval(Ne,1e3);return()=>clearInterval(Ke)},[y==null?void 0:y.status,y==null?void 0:y.publishedAt]);const Ar=_e!==null&&_e<=0,nn=_e!==null&&_e>0?`${Math.floor(_e/6e4)}:${String(Math.floor(_e%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),f.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(A&&!y)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const da=(L==="edit"?se:(y==null?void 0:y.content)??"").length,Ki=t==="genesis.md",sr=t?/^plot-\d+\.md$/.test(t):!1,Vi=c==="cartoon"&&sr,rn=c==="cartoon"&&Ki,fa=rn||Vi,ki=(y==null?void 0:y.status)==="published"||(y==null?void 0:y.status)==="published-not-indexed",pa=rn?li?li.total:null:Vi?F===null?null:Ee:null,ma=eM({fileName:t??"",contentType:c,hasGenesis:x,isPublished:ki,cutCount:pa,cutProgress:rn?li:null}),ga=(rn||Vi)&&!ki,$n=ga?xm({fileName:t,fileContent:(y==null?void 0:y.content)??"",storySlug:e??"",structureContent:we,contentType:"cartoon",episodeTitle:mt}):null,_a=!!$n&&jo($n,t),fl=Vi&&!ki&&!_m({fileContent:(y==null?void 0:y.content)??"",episodeTitle:mt}),Fn=rn&&!ki?mm((y==null?void 0:y.content)??""):null,Po=!!Fn&&Fn.blockers.length>0,Io="w-full max-w-[32rem] rounded-xl border px-3 py-3",Ho={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},xa=ee=>{if(!rn)return null;const Se=eD({hasSelectedCover:!!H,invalid:Ce==="invalid",attached:ee});return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Se.state,children:[f.jsx("span",{className:`text-[11px] font-medium ${Ho[Se.tone]}`,children:Se.label}),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),f.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:JM})]})]})},pl=_a||fl,Wu=()=>{if(!ga||!$n)return null;const ee=Ki?"Story title":"Episode title";return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":_a?"true":"false","data-blocked":pl?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[ee,":"]})," ",f.jsx("span",{className:pl?"text-error font-medium":"text-foreground",children:$n})]}),_a?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Ki?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):fl?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",$n,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},ba=()=>Fn?f.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Po?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),Fn.blockers.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ee},`b-${Se}`)),Fn.warnings.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ee},`w-${Se}`))]}):null,sn=Ki||sr?1e4:null,is=!ki&&sn!==null&&da>sn,ml=(y==null?void 0:y.content)??"",ar=ki?{count:0,warnings:[]}:dD(ml),Rr=f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsx("textarea",{ref:Mt,value:se,onChange:ee=>{W(ee.target.value),j(!0),zt.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),f.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-muted",children:I?"Unsaved changes":"No changes"}),f.jsx("button",{onClick:rr,disabled:!I||G,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:G?"Saving...":"Save"})]})]});return f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"border-b border-border",children:[f.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[_&&f.jsx("button",{onClick:_,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),f.jsxs("span",{children:[e,"/",t]}),(y==null?void 0:y.status)==="published"&&f.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(y==null?void 0:y.status)==="published-not-indexed"&&f.jsx("span",{className:"text-amber-700 font-medium",title:y.indexError,children:"Published (not indexed)"}),(y==null?void 0:y.status)==="pending"&&f.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:`text-xs font-mono ${is?"text-error font-medium":"text-muted"}`,children:[da.toLocaleString(),sn!==null?`/${sn.toLocaleString()}`:" chars"]}),is&&f.jsxs("span",{className:"text-error text-xs font-medium",children:[(da-sn).toLocaleString()," over limit"]})]})]}),f.jsxs("div",{className:"flex px-3 gap-1",children:[f.jsx("button",{onClick:()=>O("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${L==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),f.jsxs("button",{onClick:()=>O("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${L==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",I&&f.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),c==="cartoon"&&e&&t&&f.jsx(XM,{storyName:e,fileName:t,authFetch:i,refreshKey:Ae,onAction:Hn}),L==="preview"?Vi?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>$("publish"),className:`px-2 py-0.5 text-[11px] rounded ${J==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),f.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>$("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${J==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:J==="publish"?f.jsx(rM,{content:(y==null?void 0:y.content)??"",stage:F}):f.jsx(U3,{storyName:e,fileName:t,authFetch:i,onEditCut:U})})]}):f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:y!=null&&y.content?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Z0,{remarkPlugins:[J0,wS],rehypePlugins:[[NS,cD]],children:y.content})}):f.jsx("p",{className:"text-muted italic",children:"No content"})}):Vi?f.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:f.jsx(uy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)})}):rn?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>X("text"),className:`px-2 py-0.5 text-[11px] rounded ${M==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),f.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>X("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${M==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:M==="cuts"?f.jsx(uy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)}):Rr})]}):Rr,f.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?f.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:ma}):(y==null?void 0:y.status)==="published-not-indexed"?f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Ar&&f.jsx("button",{onClick:async()=>{if(!(!e||!t||!y.txHash)){B(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:y.txHash,content:y.content,storylineId:y.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:y.txHash,storylineId:y.storylineId,contentCid:"",gasCost:""})}),mi())}catch{}B(!1)}},disabled:z,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:z?"Retrying...":`Retry Index${nn?` (${nn})`:""}`}),sr&&f.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`)}const US=12e3,EM=5,NM=6e4,TM=6e4,jM=5;function AM(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function RM(e,t=US){return Math.min(t*2**e,NM)}const $S=e=>new Promise(t=>setTimeout(t,e));async function MM(e,t={}){var c;const i=t.sleep??$S,s=t.maxRetries??EM,a=t.baseDelayMs??US;let o=0;for(;;){const h=await e();if(h.ok||!AM(h.status,h.errorMessage)||o>=s)return h;const p=RM(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function DM(e={}){const t=e.limit??jM,i=e.windowMs??TM,s=e.sleep??$S,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const d=o[0]+i-a();d>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:d}),await s(d)),c()}o.push(a())}}const Dp=1024*1024;function uy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function BM(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await uy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Dp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await uy(e,"image/jpeg",s);if(a.size<=Dp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const LM=["image/webp","image/jpeg"];function FS(e){return LM.includes(e.type)&&e.size<=Dp}async function OM(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function qu(e){if(FS(e))return e;const t=await OM(e);return BM(t)}function zM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function PM(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter(zM):[]}async function IM(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function HM(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function UM(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function $M(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function FM({image:e,authFetch:t}){const i=HM(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?f.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):f.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function qM({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const D=await PM(e);E||o(D)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),y=Date.now(),N=async E=>{h(null),d(E.token);try{const D=await IM(e,E);await i(D)}catch(D){h(D instanceof Error?D.message:"Could not import the generated image")}finally{d(null)}},A=a!==null&&a.length>0;return f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),f.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),A&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"search",value:_,onChange:E=>x(E.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),f.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),A&&v.length===0&&f.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),A&&v.length>0&&f.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>f.jsxs("li",{"data-testid":`codex-image-${E.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[f.jsx(FM,{image:E,authFetch:e}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("p",{className:"text-[11px] text-foreground",children:[$M(E.mtimeMs,y)," · ",UM(E.size)]}),f.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),f.jsx("button",{onClick:()=>N(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&f.jsx("p",{className:"text-[11px] text-error",children:c})]})}const WM={done:"✓",current:"▸",todo:"○"};function GM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var N;if(!e||e.steps.length===0)return null;const p=IS(t),d=((N=e.steps.find(A=>A.key==="upload"))==null?void 0:N.status)==="done",_=d&&c&&!h,x=h||c?"done":d?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(A=>A.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],y=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode";return f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/50 space-y-2 flex-shrink-0","data-testid":"finish-episode-panel",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&f.jsxs("span",{className:"text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]})]}),f.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(A=>f.jsxs("li",{"data-testid":`finish-step-${A.key}`,"data-status":A.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${A.status==="current"?"border-accent/40 bg-accent/10 text-accent":A.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[f.jsx("span",{"aria-hidden":!0,children:WM[A.status]}),f.jsx("span",{children:A.label}),A.detail&&f.jsxs("span",{className:"text-muted",children:["· ",A.detail]})]},A.key))}),f.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-3 py-1 text-xs border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:y}),p.length>0&&f.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(A=>f.jsxs("div",{"data-testid":`finish-issue-group-${A.key}`,className:"text-[10px]",children:[f.jsx("p",{className:"font-medium text-amber-700",children:A.title}),f.jsx("ul",{className:"ml-3 list-disc text-muted",children:A.lines.map((E,D)=>f.jsx("li",{children:E},D))})]},A.key))})]})}function YM(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function qS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":Er(e)?"text":"missing"}const KM={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},VM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function XM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:Er(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function ZM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:d,syncing:_,staleMessages:x,onRepairStale:b,repairing:v,conversionPng:y,onConvert:N,converting:A,rowRef:E}){var De;const D=w.useRef(null),[P,J]=w.useState(!1),[q,L]=w.useState(null),[Z,he]=w.useState(!1),[ye,U]=w.useState(!1),[re,W]=w.useState(!1),[G,X]=w.useState(!1),[I,j]=w.useState("manual"),[O,B]=w.useState(!1),xe=qS(e),T=x.length>0,R=!!y,Y=w.useCallback(async()=>{y&&(X(!0),await N(e.id,y),X(!1),c())},[y,N,e.id,c]),C=w.useCallback(async Ee=>{J(!0),L(null);try{let Be=Ee;if(!FS(Ee))try{Be=await qu(Ee)}catch(tt){return L(tt instanceof Error?tt.message:"Could not import image"),!1}const je=Be.type==="image/jpeg"?"jpg":"webp",Ze=new FormData;Ze.append("file",new File([Be],`clean.${je}`,{type:Be.type}));const Ce=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ze});if(!Ce.ok){const tt=await Ce.json();return L(tt.error||"Upload failed"),!1}return c(),!0}catch{return L("Upload failed"),!1}finally{J(!1)}},[o,t,i,e.id,c]),se=XM(e,R,T),te=e.cleanImagePath??y??null,oe=((De=e.overlays)==null?void 0:De.length)??0,$=!Er(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!T&&!R,ue=w.useCallback(()=>{var Ee;(Ee=navigator.clipboard)==null||Ee.writeText(kM(e,i)),B(!0),setTimeout(()=>B(!1),2e3)},[e,i]),be=se.key==="convert"?{label:G?"Converting…":"Convert image",onClick:Y,testid:`card-convert-${e.id}`}:se.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:se.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:se.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null;return f.jsxs("div",{ref:E,"data-cut-row":e.id,className:`border rounded ${s?"border-accent/30":"border-border"}`,children:[f.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[f.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[f.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${VM[se.tone]}`}),f.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),f.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${KM[se.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:se.label})]}),te?f.jsx(Rp,{storyName:t,assetPath:te,authFetch:o,alt:`Cut ${e.id} artwork`,className:"w-full max-h-44 object-contain rounded border border-border bg-white"}):f.jsx("div",{className:"w-full h-20 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:Er(e)?"Text panel — no artwork needed":"No artwork yet"}),f.jsx("button",{onClick:a,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),$&&f.jsxs("div",{className:"space-y-1","data-testid":`lettering-${e.id}`,children:[f.jsx("div",{className:"text-[10px] font-medium text-muted uppercase tracking-wider",children:"Lettering"}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="manual",onChange:()=>j("manual"),"data-testid":`lettering-mode-manual-${e.id}`}),"Manual — I place bubbles myself"]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="ai",onChange:()=>j("ai"),"data-testid":`lettering-mode-ai-${e.id}`}),"AI draft — ask the agent to place initial bubbles"]}),I==="ai"&&f.jsx("p",{className:"text-[10px] text-muted",children:"Paste it to your agent, then review the draft bubbles here and export the final cut."})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[$?I==="manual"?f.jsx("button",{onClick:h,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:oe>0?"Review lettering":"Add speech bubbles"}):f.jsx("button",{onClick:ue,"data-testid":`copy-lettering-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded border border-accent/40 text-accent hover:bg-accent/5",children:O?"Copied!":"Copy AI lettering prompt"}):be?f.jsx("button",{onClick:be.onClick,disabled:se.key==="convert"&&(G||A),"data-testid":be.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:be.label}):null,f.jsx("button",{onClick:a,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:s?"Hide details":"Open details"})]})]}),s&&f.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[R&&f.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[f.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),f.jsx("button",{onClick:Y,disabled:G||A,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:G?"Converting…":"Convert image"})]}),T&&!R&&f.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[x.map((Ee,Be)=>f.jsx("p",{className:"text-[11px] text-error",children:Ee},Be)),f.jsx("button",{onClick:b,disabled:v,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:v?"Repairing…":"Clear stale path"})]}),!Er(e)&&f.jsxs("div",{className:"mt-2 space-y-2",children:[f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(cy(e,i)),he(!0),setTimeout(()=>he(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:Z?"Copied!":"Copy Codex task"}),f.jsx("input",{ref:D,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ee=>{var je;const Be=(je=Ee.target.files)==null?void 0:je[0];Be&&C(Be),Ee.target.value=""}}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("button",{onClick:()=>{var Ee;return(Ee=D.current)==null?void 0:Ee.click()},disabled:P,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:P?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),f.jsx("button",{onClick:()=>W(Ee=>!Ee),disabled:P,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:re?"Hide Codex images":"Import from Codex"})]}),re&&f.jsx(qM,{authFetch:o,cutId:e.id,onImport:async Ee=>{await C(Ee)&&W(!1)},onClose:()=>W(!1)}),!e.cleanImagePath&&f.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),xe==="missing"&&f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),f.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",f.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(cy(e,i)),U(!0),setTimeout(()=>U(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:ye?"Copied!":"Copy Codex task"})]}),xe==="missing"&&p&&f.jsx("button",{onClick:d,disabled:_,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:_?"Syncing...":"Found local clean image — sync to cut plan"}),q&&f.jsx("p",{className:"text-xs text-error mt-1",children:q})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||Er(e))&&f.jsx("button",{onClick:h,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&f.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&f.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ee,Be)=>f.jsxs("p",{children:[f.jsxs("span",{className:"font-medium",children:[Ee.speaker,":"]})," ",Ee.text]},Be))}),e.narration&&f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function hy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h}){var Gt,mn;const[p,d]=w.useState(null),_=w.useRef(o);_.current=o;const x=w.useRef(h);x.current=h;const[b,v]=w.useState(!0),[y,N]=w.useState(null),[A,E]=w.useState(null),[D,P]=w.useState(null),[J,q]=w.useState(!1),[L,Z]=w.useState([]),[he,ye]=w.useState(!1),[U,re]=w.useState(""),[W,G]=w.useState({markdownReady:!1,published:!1}),[X,I]=w.useState(!1),[j,O]=w.useState(!1),[B,xe]=w.useState(!1),[T,R]=w.useState(null),[Y,C]=w.useState(null),[se,te]=w.useState(new Set),[oe,$]=w.useState(new Map),[ue,be]=w.useState(!1),[De,Ee]=w.useState(null),[Be,je]=w.useState(!1),[Ze,Ce]=w.useState(null),tt=w.useRef(new Map),pt=w.useRef(null),Ge=t.replace(/\.md$/,"");w.useEffect(()=>{var de;c&&pt.current!==c.seq&&(pt.current=c.seq,c.openEditor?P(c.cutId):(E(c.cutId),Ce(c.cutId)),(de=x.current)==null||de.call(x))},[c]),w.useEffect(()=>{var Re;if(Ze==null)return;const de=tt.current.get(Ze);de&&((Re=de.scrollIntoView)==null||Re.call(de,{behavior:"smooth",block:"center"}),Ce(null))},[Ze,p]);const Ae=w.useCallback(async()=>{var de;try{const Re=await i(`/api/stories/${e}/cuts/${Ge}`);if(Re.status===404){d(null);return}if(!Re.ok){const st=await Re.json();N(st.error||"Failed to load cuts");return}const We=await Re.json();d(We),N(null);try{const st=await i(`/api/stories/${e}/${t}`);if(st.ok){const nt=await st.json(),ct=typeof(nt==null?void 0:nt.content)=="string"?nt.content:"",ae=Array.isArray(We==null?void 0:We.cuts)?We.cuts:[],we=ct.length>0&&zS(ct,ae).ready,ze=(nt==null?void 0:nt.status)==="published"||(nt==null?void 0:nt.status)==="published-not-indexed";G({markdownReady:we,published:ze})}else G({markdownReady:!1,published:!1})}catch{G({markdownReady:!1,published:!1})}(de=_.current)==null||de.call(_)}catch{N("Failed to load cuts")}finally{v(!1)}},[i,e,Ge,t]),Ve=w.useCallback(async()=>{be(!1);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/detect-clean-images`);if(!de.ok)return;const Re=await de.json();te(new Set(Array.isArray(Re.detected)?Re.detected:[]));const We=new Map,st=Re.stale;if(Array.isArray(st))for(const nt of st){if(typeof(nt==null?void 0:nt.cutId)!="number"||typeof(nt==null?void 0:nt.message)!="string")continue;const ct=We.get(nt.cutId)??[];ct.push(nt.message),We.set(nt.cutId,ct)}$(We),be(!0)}catch{}},[i,e,Ge]),At=w.useCallback(async()=>{Ee(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/asset-diagnostics`);if(!de.ok)return;const Re=await de.json();Ee(Array.isArray(Re.diagnostics)?Re.diagnostics:null)}catch{}},[i,e,Ge]),Ot=w.useCallback(async()=>{je(!0);try{await Promise.all([Ae(),Ve(),At()])}finally{je(!1)}},[Ae,Ve,At]),ci=w.useCallback(async()=>{I(!0),C(null),Z([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/sync-clean-images`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Sync failed");else{const We=Array.isArray(Re.synced)?Re.synced.length:0,st=Array.isArray(Re.cleared)?Re.cleared.length:0,nt=Array.isArray(Re.rejected)?Re.rejected:[];nt.length>0&&Z(nt.map(ae=>`Cut ${ae.cutId}: ${ae.reason}`));const ct=[];We>0&&ct.push(`Synced ${We}`),st>0&&ct.push(`Cleared ${st} stale path${st===1?"":"s"}`),C(ct.length>0?ct.join(", "):"No new clean images"),await Ae(),await Ve(),await At()}}catch{C("Sync failed")}I(!1)},[i,e,Ge,Ae,Ve,At]),St=w.useCallback(async(de,Re)=>{try{const We=await i(AS(e,Re));if(!We.ok)return!1;const st=await We.blob(),nt=await qu(new File([st],"clean.png",{type:st.type||"image/png"})),ct=nt.type==="image/jpeg"?"jpg":"webp",ae=new FormData;return ae.append("file",new File([nt],`clean.${ct}`,{type:nt.type})),(await i(`/api/stories/${e}/cuts/${Ge}/upload-clean/${de}`,{method:"POST",body:ae})).ok}catch{return!1}},[i,e,Ge]),fi=w.useCallback(async de=>{xe(!0),R(null);let Re=0;const We=[];for(const st of de)await St(st.cutId,st.pngPath)?Re++:We.push(st.cutId);await Ot(),xe(!1),R(We.length===0?`Converted ${Re} image${Re===1?"":"s"} to WebP`:`Converted ${Re}; ${We.length} failed (Cut ${We.join(", ")}) — try Convert image on each`)},[St,Ot]),ne=w.useCallback(async()=>{var nt;if(!p)return;ye(!0),re(""),Z([]);const de=p.cuts.filter(ct=>ct.finalImagePath&&!ct.uploadedCid),Re=[],We=DM({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:ct})=>re(`Upload limit reached — waiting ${Math.round(ct/1e3)}s before continuing…`)});for(let ct=0;ct{const Xe=await i("/api/publish/upload-plot-image",{method:"POST",body:_t});if(Xe.ok){const{cid:qt,url:gi}=await Xe.json();return{ok:!0,status:Xe.status,cid:qt,url:gi}}const zt=await Xe.json().catch(()=>({}));return{ok:!1,status:Xe.status,errorMessage:zt.error}},{...a,onWaiting:({attempt:Xe,maxRetries:zt,waitMs:qt})=>re(`Cut ${ae.id} rate-limited — waiting ${Math.round(qt/1e3)}s before retry ${Xe}/${zt}...`)});if(!Je.ok){Re.push(`Cut ${ae.id}: upload failed — ${Je.errorMessage||"unknown"}`);continue}const{cid:ut,url:at}=Je;(await i(`/api/stories/${e}/cuts/${Ge}/set-uploaded/${ae.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:ut,url:at})})).ok||Re.push(`Cut ${ae.id}: failed to record upload`)}catch(we){Re.push(`Cut ${ae.id}: ${we instanceof Error?we.message:"failed"}`)}}if(Re.length>0){Z(Re),ye(!1),re(""),Ae();return}re("Preparing episode for publishing…");const st=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(st.ok){const ct=await st.json();((nt=ct.warnings)==null?void 0:nt.length)>0&&Z(ct.warnings)}ye(!1),re(""),Ae()},[p,i,e,Ge,a,Ae]),_e=w.useCallback(async()=>{O(!0),C(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/repair-asset-paths`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Repair failed");else{const We=Array.isArray(Re.cleared)?Re.cleared.length:0;C(We>0?`Cleared ${We} stale path${We===1?"":"s"}`:"No stale paths to clear"),await Ae(),await Ve()}}catch{C("Repair failed")}O(!1)},[i,e,Ge,Ae,Ve]),[Pe,Fe]=w.useState(!1),Qe=w.useCallback(async()=>{if(p){Fe(!0);try{const de=p.cuts.reduce((nt,ct)=>Math.max(nt,ct.id),0)+1,Re={id:de,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},We={...p,cuts:[...p.cuts,Re]},st=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(We)});if(st.ok)E(de),await Ae();else{const nt=await st.json().catch(()=>({}));C(nt.error||"Could not add text panel")}}catch{C("Could not add text panel")}Fe(!1)}},[p,i,e,Ge,Ae]);if(w.useEffect(()=>{Ae(),Ve(),At()},[Ae,Ve,At]),b)return f.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(y)return f.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:y}),f.jsxs("p",{className:"text-xs text-muted",children:[Ge,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),f.jsx("button",{onClick:Ae,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!p||p.cuts.length===0)return f.jsxs("div",{className:"p-4 text-center space-y-1",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const H=D!==null?p.cuts.find(de=>de.id===D):null;if(H)return f.jsx(bM,{storyName:e,cut:H,plotFile:Ge,language:s,authFetch:i,onSave:async de=>{const Re={...p,cuts:p.cuts.map(st=>st.id===D?{...st,overlays:de}:st)},We=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Re)});if(!We.ok){const st=await We.json().catch(()=>({}));throw new Error(st.error||"Failed to save overlays")}},onExported:()=>Ae(),onClose:()=>{P(null),Ae()}});const ge=p.cuts.reduce((de,Re)=>{const We=qS(Re);return de[We]++,de},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),Te=p.cuts.filter(de=>!Er(de)).length,me=p.cuts.filter(de=>LS(de)).map(de=>de.id),He=eM({cuts:p.cuts,published:W.published}),Le=((Gt=He.steps.find(de=>de.key==="upload"))==null?void 0:Gt.status)==="done",ht=p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)||Le&&!W.markdownReady,it=(De??[]).filter(de=>de.state==="needs-conversion"&&de.convertiblePng).map(de=>({cutId:de.cutId,pngPath:de.convertiblePng})),Mt=new Map(it.map(de=>[de.cutId,de.pngPath])),Dt=(De??[]).filter(de=>de.state==="needs-conversion"&&de.issue).map(de=>de.issue),pi=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mn=Ge.match(/\d+/))==null?void 0:mn[0])??"0",10)+1}`,kt=typeof p.title=="string"?p.title:null,ki=p.cuts.filter(de=>!Er(de)),mi={cuts:p.cuts.length,artwork:ki.filter(de=>de.cleanImagePath||Mt.has(de.id)).length,converted:ki.filter(de=>de.cleanImagePath&&/\.(webp|jpe?g)$/i.test(de.cleanImagePath)).length,lettered:p.cuts.filter(de=>{var Re;return(((Re=de.overlays)==null?void 0:Re.length)??0)>0||!!de.finalImagePath}).length,uploaded:p.cuts.filter(de=>de.uploadedCid||de.uploadedUrl).length};return f.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[f.jsxs("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"font-serif text-foreground truncate",children:pi}),kt&&f.jsxs("span",{className:"text-muted truncate",children:["· ",kt]})]}),f.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[mi.cuts," cuts · ",mi.artwork," artwork found · ",mi.converted," converted · ",mi.lettered," lettered · ",mi.uploaded," uploaded"]})]}),f.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[f.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),f.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[f.jsxs("span",{className:"font-mono text-muted",children:[p.cuts.length," cuts"]}),ge.missing>0&&f.jsxs("span",{className:"text-muted",children:[ge.missing," missing"]}),ge.clean>0&&f.jsxs("span",{className:"text-green-700",children:[ge.clean," clean"]}),ge.lettered>0&&f.jsxs("span",{className:"text-amber-700",children:[ge.lettered," lettered"]}),ge.uploaded>0&&f.jsxs("span",{className:"text-green-700",children:[ge.uploaded," uploaded"]}),ge.text>0&&f.jsxs("span",{className:"text-accent",children:[ge.text," text ",ge.text===1?"panel":"panels"]}),f.jsx("button",{onClick:async()=>{q(!0),Z([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(de.ok){const Re=await de.json();Z(Re.warnings||[])}}catch{}q(!1)},disabled:J,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:J?"Preparing…":"Prepare episode for publish"}),f.jsx("button",{onClick:Qe,disabled:Pe,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:Pe?"Adding…":"Add narration/text panel"}),f.jsx("button",{onClick:Ot,disabled:Be,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:Be?"Checking…":"Refresh assets"}),f.jsx("button",{onClick:ci,disabled:X,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:X?"Syncing...":"Sync clean images"}),f.jsx("button",{onClick:ne,disabled:he||!(p!=null&&p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:U||"Upload & Prepare for Publish"})]})]}),f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",f.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," for a narration or title card. It becomes a solid card exported as a final image."]})]}),me.length>0&&f.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[me.length===1?"Cut":"Cuts"," ",me.join(", ")," ",me.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export ",me.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),ue&&Te>0&&ge.missing===0&&oe.size===0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[f.jsx("span",{"aria-hidden":!0,children:"✓"}),f.jsxs("span",{children:["All ",Te," clean image",Te===1?"":"s"," present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),Y&&f.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:Y}),it.length>0&&f.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[it.length," PNG image",it.length===1?"":"s"," found"]}),f.jsx("button",{onClick:()=>fi(it),disabled:B,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:B?"Converting…":"Convert all to WebP"})]}),f.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),T&&f.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:T}),Dt.length>0&&f.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[f.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Dt.map((de,Re)=>f.jsx("li",{children:de},Re))})]})]}),De&&De.length>0&&(()=>{const de=YM(De),Re=De.filter(We=>We.state==="missing");return f.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[f.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",de.uploaded," uploaded · ",de.finalReady," final · ",de.cleanReady," clean · ",de.planned," planned",de.needsConversion>0?` · ${de.needsConversion} needs conversion`:"",de.missing>0?` · ${de.missing} missing`:""]}),Re.length>0&&f.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:Re.map(We=>f.jsx("li",{children:We.issue},We.cutId))})]})})(),f.jsx(GM,{checklist:He,issues:L,onFinish:ne,finishing:he,progressText:U,canFinish:ht,markdownReady:W.markdownReady,published:W.published}),f.jsx("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-2","data-testid":"cut-list-scroll",children:p.cuts.map(de=>f.jsx(ZM,{cut:de,storyName:e,plotFile:Ge,expanded:A===de.id,onToggle:()=>E(A===de.id?null:de.id),authFetch:i,onUpdated:()=>{Ae(),Ve(),At()},onOpenEditor:()=>P(de.id),detectedLocalClean:se.has(de.id),onSyncClean:ci,syncing:X,staleMessages:oe.get(de.id)??[],onRepairStale:_e,repairing:j,conversionPng:Mt.get(de.id)??null,onConvert:St,converting:B,rowRef:Re=>{Re?tt.current.set(de.id,Re):tt.current.delete(de.id)}},de.id))})]})}function xm({coach:e,onAction:t,className:i="",showEmptyState:s=!1}){const[a,o]=w.useState(null),c=a!==null&&a===(e==null?void 0:e.prompt);return e===void 0?null:e?f.jsx("div",{className:`m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm ${i}`,"data-testid":"workflow-coach","data-stage":e.stageLabel,"data-action-kind":e.actionKind,"data-ui-action":e.uiAction??"",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent","data-testid":"workflow-coach-stage",children:e.stageLabel}),f.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"workflow-coach-action",children:[f.jsx("span",{className:"font-semibold",children:"Next: "}),f.jsx("span",{children:e.action})]}),c&&f.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:"Prompt copied."})]}),e.actionKind==="agent"&&e.prompt?f.jsx("button",{onClick:()=>{var p;if(!e.prompt)return;const h=e.prompt;(p=navigator.clipboard)==null||p.writeText(h).then(()=>o(h)).catch(()=>{})},"data-testid":"workflow-coach-copy",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):e.actionKind==="ui"&&e.uiAction?f.jsx("button",{onClick:()=>t(e.uiAction,e.episodeFile),"data-testid":"workflow-coach-do",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):null]})}):s?f.jsx("div",{className:`m-3 rounded-lg border border-green-700/25 bg-green-950/5 px-4 py-3 ${i}`,"data-testid":"workflow-coach","data-state":"complete",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("span",{className:"rounded-full bg-green-700/10 px-2 py-1 text-[10px] font-bold uppercase tracking-[0.16em] text-green-700",children:"Complete"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No next action available"}),f.jsx("p",{className:"mt-0.5 text-xs text-muted",children:"This workflow has no queued next step right now."})]})]})}):null}function QM({storyName:e,fileName:t,authFetch:i,refreshKey:s=0,onAction:a,showEmptyState:o=!1}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,t??"",s]),[d,_]=w.useState(null);return d!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=t?`?focus=${encodeURIComponent(t)}`:"";return i(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h((v==null?void 0:v.coach)??null)}).catch(()=>{}),()=>{x=!0}},[e,t,i,s]),f.jsx(xm,{coach:c,onAction:a,showEmptyState:o})}const JM=1024*1024,eD=["image/webp","image/jpeg"],tD="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function iD(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function dy(e){return e.size>JM?"Image exceeds 1MB limit":eD.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function nD(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Bp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function rD(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function jo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function sD(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Lp(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function _m(e){var s;const t=Bp(e.fileContent);if(t)return!Lp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Lp(i)}function bm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Bp(i);if(t==="genesis.md"){const p=a?Bp(a):null;return(h??p??rD(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),d=sD(t);return((p||d)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function aD(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function lD(e){return aD(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function fy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function oD(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Mf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Df(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function cD(e){return!!e&&e.ready===!1}function uD(e){const t=Df(e.requiredBalance)??Df(e.creationFee),i=Df(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const hD={...ll,attributes:{...ll.attributes,img:["src","alt","title"]}},dD="https://ipfs.filebase.io/ipfs/";function fD(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function pD(e){const t=fD(e),i=[];for(const a of t)a.url.startsWith(dD)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function mD({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:d,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v}){const[y,N]=w.useState(null),[A,E]=w.useState(!1),[D,P]=w.useState("preview"),[J,q]=w.useState("publish"),[L,Z]=w.useState("text"),[he,ye]=w.useState(null),U=w.useCallback((ee,Se)=>{P("edit"),ye(Ne=>({cutId:ee,openEditor:Se,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[re,W]=w.useState(""),[G,X]=w.useState(!1),[I,j]=w.useState(!1),[O,B]=w.useState(!1),[xe,T]=w.useState(null),[R,Y]=w.useState(""),[C,se]=w.useState(""),[te,oe]=w.useState(!1),[$,ue]=w.useState(null),[be,De]=w.useState(0),[Ee,Be]=w.useState(0),[je,Ze]=w.useState(null),[Ce,tt]=w.useState(null),[pt,Ge]=w.useState(null),[Ae,Ve]=w.useState(0),At=w.useRef(null),Ot=w.useRef(!1),[ci,St]=w.useState(!1),[fi,ne]=w.useState(nl[0]),[_e,Pe]=w.useState(Xr[0]),[Fe,Qe]=w.useState(!1),[H,ge]=w.useState(null),[Te,me]=w.useState(null),[He,Le]=w.useState(!1),[ht,it]=w.useState(!1),[Mt,Dt]=w.useState(!1),[pi,kt]=w.useState(null),[ki,mi]=w.useState(!1),Gt=w.useRef(null),mn=w.useRef(null),[de,Re]=w.useState(!1),[We,st]=w.useState(null),[nt,ct]=w.useState(null),[ae,we]=w.useState("unknown"),ze=w.useRef(!1),[Rt,_t]=w.useState(!1),[Je,ut]=w.useState(!1),[at,wt]=w.useState(null),[Xe,zt]=w.useState([]),[qt,gi]=w.useState(null),Tn=w.useRef(null),mr=w.useRef(null),$i=w.useCallback(async()=>{if(!e||!t){N(null);return}const ee=`${e}/${t}`,Se=mr.current!==ee;Se&&(mr.current=ee);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Ke=await Ne.json();N(Ke),(Se||!Ot.current)&&(W(Ke.content??""),Se&&(j(!1),Ot.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{E(!0),$i().finally(()=>E(!1))},[$i]),w.useEffect(()=>{if(!e||!t||D==="edit"&&I)return;const ee=setInterval($i,3e3);return()=>clearInterval(ee)},[e,t,$i,D,I]);const[ei,jn]=w.useState(null),Fn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Fn||!e){jn(null);return}let ee=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||jn(Se?Mp(Se.cuts||[]):null)}).catch(()=>{ee||jn(null)}),()=>{ee=!0}},[Fn,e,i]);const ti=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!ti||!e||!t){ue(null),De(0),Be(0),Ze(null);return}let ee=!1;const Se=t.replace(/\.md$/,"");return Ze(null),(async()=>{try{const[Ne,Ke]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Se}`)]);if(ee)return;if(!Ke.ok){ue("error"),De(0),Be(0),Ze(null);return}const Et=await Ke.json(),xi=Et.cuts||[],Rn=Ne.ok?(await Ne.json()).content??"":"",on=PS(Rn,xi);ee||(ue(on.stage),De(on.awaitingCount),Be(on.totalCuts),Ze(Mp(xi)),Ge(typeof Et.title=="string"?Et.title:null))}catch{ee||(ue("error"),De(0),Be(0),Ze(null))}})(),()=>{ee=!0}},[ti,e,t,i,y==null?void 0:y.content,y==null?void 0:y.status,Ae]),w.useEffect(()=>{if(!e){tt(null);return}let ee=!1;return i(`/api/stories/${e}/structure.md`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||tt((Se==null?void 0:Se.content)??null)}).catch(()=>{}),()=>{ee=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ee=bu(p);let Se=ee??"";if(!ee&&Ce){const Ke=Ce.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Ke&&(Se=bu(Ke[1].replace(/\*+/g,"").trim())??"")}Y(Se);let Ne=h&&Xr.find(Ke=>Ke.toLowerCase()===h.toLowerCase())||"";if(!Ne&&Ce){const Ke=Ce.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Ke&&(Ne=Xr.find(Et=>Et.toLowerCase()===Ke[1].replace(/\*+/g,"").trim().toLowerCase())||"")}se(Ne),oe(d??!1)},[e,p,h,d,Ce]);const Yt=w.useCallback(ee=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}).catch(()=>{})},[e,i]),qn=w.useCallback(async()=>{if(!(!e||!t)){X(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:re})})).ok&&(j(!1),Ot.current=!1,N(Se=>Se&&{...Se,content:re}))}catch{}X(!1)}},[e,t,i,re]),sn=w.useCallback(async()=>{if(!e||!t)return;const ee=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ee}/generate-markdown`,{method:"POST"})).ok&&(await $i(),Ve(Ne=>Ne+1))}catch{}},[e,t,i,$i]),An=w.useCallback((ee,Se)=>{if(ee==="view-progress"){x==null||x();return}if(Se&&Se!==t){b==null||b(Se);return}switch(ee){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":P("edit"),Z("cuts");break;case"generate-markdown":sn();break;case"publish":P("preview");break}},[t,x,b,sn]),ts=w.useCallback(ee=>{var Ke;const Se=(Ke=ee.target.files)==null?void 0:Ke[0];if(!Se)return;ze.current=!0,st(null),ct(null);const Ne=dy(Se);if(Ne){ge(null),me(Et=>(Et&&URL.revokeObjectURL(Et),null)),Gt.current&&(Gt.current.value=""),kt(Ne),we("invalid");return}ge(Se),me(Et=>(Et&&URL.revokeObjectURL(Et),URL.createObjectURL(Se))),kt(null),we("selected")},[]),Zt=w.useCallback(async ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];if(mn.current&&(mn.current.value=""),!(!Se||!e)){ze.current=!0,st(null),Re(!0),kt(null);try{let Ke;try{Ke=await qu(Se)}catch(cr){ge(null),me(Ls=>(Ls&&URL.revokeObjectURL(Ls),null)),kt(cr instanceof Error?cr.message:"Could not import image");return}const Et=Ke.type==="image/jpeg"?"jpg":"webp",xi=new File([Ke],`cover.${Et}`,{type:Ke.type}),Rn=new FormData;Rn.append("file",xi);const on=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Rn});if(!on.ok){const cr=await on.json().catch(()=>({}));kt(cr.error||"Cover import failed");return}ge(xi),me(cr=>(cr&&URL.revokeObjectURL(cr),URL.createObjectURL(xi))),ct(null),we("selected"),kt(null)}catch{kt("Cover import failed")}finally{Re(!1)}}},[e,i]),gn=w.useCallback(async ee=>{if(ee.size>1024*1024){wt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ee.type)){wt("Only WebP and JPEG images are accepted");return}ut(!0),wt(null);try{const Ne=new FormData;Ne.append("file",ee);const Ke=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Ke.ok){const xi=await Ke.json();throw new Error(xi.error||"Upload failed")}const Et=await Ke.json();zt(xi=>[...xi,{cid:Et.cid,url:Et.url}])}catch(Ne){wt(Ne instanceof Error?Ne.message:"Upload failed")}finally{ut(!1),Tn.current&&(Tn.current.value="")}},[i]),dl=w.useCallback(ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];Se&&gn(Se)},[gn]),Ar=w.useCallback(async()=>{if(y!=null&&y.storylineId){Le(!0),kt(null),mi(!1);try{let ee;if(H){const Ne=new FormData;Ne.append("file",H);const Ke=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Ke.ok){const xi=await Ke.json();throw new Error(xi.error||"Cover upload failed")}ee=(await Ke.json()).cid}const Se=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:y.storylineId,...ee!==void 0&&{coverCid:ee},genre:fi,language:_e,isNsfw:Fe})});if(!Se.ok){const Ne=await Se.json();throw new Error(Ne.error||"Update failed")}mi(!0),ge(null),ee!==void 0&&(Dt(!0),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),we("unknown"),Gt.current&&(Gt.current.value="")),setTimeout(()=>mi(!1),3e3)}catch(ee){kt(ee instanceof Error?ee.message:"Update failed")}finally{Le(!1)}}},[y==null?void 0:y.storylineId,H,fi,_e,Fe,i]);w.useEffect(()=>{St(!1),ge(null),me(null),kt(null),mi(!1),it(!1),_t(!1),zt([]),wt(null),st(null),ct(null),we("unknown"),ze.current=!1,Z("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!y||y.storylineId||y.status==="published"||y.status==="published-not-indexed"||ze.current)return;let ee=!1;return(async()=>{try{const Se=await i(`/api/stories/${e}/cover-asset`);if(ee||!Se.ok)return;const Ne=await Se.json();if(ee)return;if(!(Ne!=null&&Ne.found)){we("none");return}if(!Ne.valid){ct(Ne.error||"Detected cover asset is invalid and was not used"),we("invalid");return}const Ke=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ee||!Ke.ok)return;const Et=await Ke.blob(),xi=new File([Et],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(dy(xi)||ee||ze.current)return;ge(xi),me(Rn=>(Rn&&URL.revokeObjectURL(Rn),URL.createObjectURL(xi))),st(Ne.path),we("detected")}catch{}})(),()=>{ee=!0}},[e,t,y,y==null?void 0:y.status,y==null?void 0:y.storylineId,i]),w.useEffect(()=>{if(!ci||!(y!=null&&y.storylineId))return;it(!1);const ee="https://plotlink.xyz";let Se=!1;return fetch(`${ee}/api/storyline/${y.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!Se){if(!Ne){kt("Could not load current story metadata");return}if(Ne.genre){const Ke=bu(Ne.genre);Ke&&ne(Ke)}if(Ne.language){const Ke=Xr.find(Et=>Et.toLowerCase()===Ne.language.toLowerCase());Ke&&Pe(Ke)}Ne.isNsfw!==void 0&&Qe(!!Ne.isNsfw),Dt(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),it(!0)}}).catch(()=>{Se||kt("Could not load current story metadata")}),()=>{Se=!0}},[ci,y==null?void 0:y.storylineId]),w.useEffect(()=>{if(D!=="edit")return;const ee=Se=>{(Se.metaKey||Se.ctrlKey)&&Se.key==="s"&&(Se.preventDefault(),qn())};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[D,qn]),w.useEffect(()=>{if((y==null?void 0:y.status)!=="published-not-indexed"||!y.publishedAt)return;const ee=new Date(y.publishedAt).getTime(),Se=300*1e3,Ne=()=>{const Et=Math.max(0,Se-(Date.now()-ee));T(Et)};Ne();const Ke=setInterval(Ne,1e3);return()=>clearInterval(Ke)},[y==null?void 0:y.status,y==null?void 0:y.publishedAt]);const ar=xe!==null&&xe<=0,xn=xe!==null&&xe>0?`${Math.floor(xe/6e4)}:${String(Math.floor(xe%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),f.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(A&&!y)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const ha=(D==="edit"?re:(y==null?void 0:y.content)??"").length,Zi=t==="genesis.md",lr=t?/^plot-\d+\.md$/.test(t):!1,Qi=c==="cartoon"&&lr,an=c==="cartoon"&&Zi,da=an||Qi,Ei=(y==null?void 0:y.status)==="published"||(y==null?void 0:y.status)==="published-not-indexed",fa=an?ei?ei.total:null:Qi?$===null?null:Ee:null,pa=iM({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Ei,cutCount:fa,cutProgress:an?ei:null}),ma=(an||Qi)&&!Ei,Wn=ma?bm({fileName:t,fileContent:(y==null?void 0:y.content)??"",storySlug:e??"",structureContent:Ce,contentType:"cartoon",episodeTitle:pt}):null,ga=!!Wn&&jo(Wn,t),fl=Qi&&!Ei&&!_m({fileContent:(y==null?void 0:y.content)??"",episodeTitle:pt}),Gn=an&&!Ei?mm((y==null?void 0:y.content)??""):null,Po=!!Gn&&Gn.blockers.length>0,Io="w-full max-w-[32rem] rounded-xl border px-3 py-3",Ho={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},xa=ee=>{if(!an)return null;const Se=iD({hasSelectedCover:!!H,invalid:ae==="invalid",attached:ee});return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Se.state,children:[f.jsx("span",{className:`text-[11px] font-medium ${Ho[Se.tone]}`,children:Se.label}),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),f.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:tD})]})]})},pl=ga||fl,Wu=()=>{if(!ma||!Wn)return null;const ee=Zi?"Story title":"Episode title";return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":ga?"true":"false","data-blocked":pl?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[ee,":"]})," ",f.jsx("span",{className:pl?"text-error font-medium":"text-foreground",children:Wn})]}),ga?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Zi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):fl?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Wn,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},_a=()=>Gn?f.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Po?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),Gn.blockers.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ee},`b-${Se}`)),Gn.warnings.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ee},`w-${Se}`))]}):null,ln=Zi||lr?1e4:null,is=!Ei&&ln!==null&&ha>ln,ml=(y==null?void 0:y.content)??"",or=Ei?{count:0,warnings:[]}:pD(ml),Rr=f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsx("textarea",{ref:At,value:re,onChange:ee=>{W(ee.target.value),j(!0),Ot.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),f.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-muted",children:I?"Unsaved changes":"No changes"}),f.jsx("button",{onClick:qn,disabled:!I||G,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:G?"Saving...":"Save"})]})]});return f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"border-b border-border",children:[f.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&f.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),f.jsxs("span",{children:[e,"/",t]}),(y==null?void 0:y.status)==="published"&&f.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(y==null?void 0:y.status)==="published-not-indexed"&&f.jsx("span",{className:"text-amber-700 font-medium",title:y.indexError,children:"Published (not indexed)"}),(y==null?void 0:y.status)==="pending"&&f.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:`text-xs font-mono ${is?"text-error font-medium":"text-muted"}`,children:[ha.toLocaleString(),ln!==null?`/${ln.toLocaleString()}`:" chars"]}),is&&f.jsxs("span",{className:"text-error text-xs font-medium",children:[(ha-ln).toLocaleString()," over limit"]})]})]}),f.jsxs("div",{className:"flex px-3 gap-1",children:[f.jsx("button",{onClick:()=>P("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),f.jsxs("button",{onClick:()=>P("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",I&&f.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),c==="cartoon"&&e&&t&&f.jsx(QM,{storyName:e,fileName:t,authFetch:i,refreshKey:Ae,onAction:An,showEmptyState:!0}),D==="preview"?Qi?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>q("publish"),className:`px-2 py-0.5 text-[11px] rounded ${J==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),f.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>q("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${J==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:J==="publish"?f.jsx(aM,{content:(y==null?void 0:y.content)??"",stage:$}):f.jsx(F3,{storyName:e,fileName:t,authFetch:i,onEditCut:U})})]}):f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:y!=null&&y.content?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Q0,{remarkPlugins:[eS,CS],rehypePlugins:[[TS,hD]],children:y.content})}):f.jsx("p",{className:"text-muted italic",children:"No content"})}):Qi?f.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:f.jsx(hy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)})}):an?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>Z("text"),className:`px-2 py-0.5 text-[11px] rounded ${L==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),f.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>Z("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${L==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:L==="cuts"?f.jsx(hy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)}):Rr})]}):Rr,f.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?f.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:pa}):(y==null?void 0:y.status)==="published-not-indexed"?f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ar&&f.jsx("button",{onClick:async()=>{if(!(!e||!t||!y.txHash)){B(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:y.txHash,content:y.content,storylineId:y.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:y.txHash,storylineId:y.storylineId,contentCid:"",gasCost:""})}),$i())}catch{}B(!1)}},disabled:O,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:O?"Retrying...":`Retry Index${xn?` (${xn})`:""}`}),lr&&f.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. Retry Publish creates a NEW on-chain transaction and a SECOND, permanent chapter on PlotLink (PlotLink content is immutable). Only do this if the chapter never appeared after indexing. -Create a new on-chain chapter anyway?`)||s==null||s(e,t,R,C,ie)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),f.jsx("p",{className:"text-muted text-xs",children:Ar?sr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":sr?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),y.indexError&&f.jsx("p",{className:"text-error text-xs",children:y.indexError})]}):(y==null?void 0:y.status)==="published"?f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-green-700",children:"Published"}),y.storylineId&&f.jsx("a",{href:(()=>{var Ne;const ee=`https://plotlink.xyz/story/${y.storylineId}`;if(!sr)return ee;const Se=y.plotIndex!=null&&y.plotIndex>0?y.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ee}/${Se}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ki&&o&&y.storylineId&&(!y.authorAddress||y.authorAddress.toLowerCase()===o.toLowerCase())&&f.jsx("button",{onClick:()=>wt(ee=>!ee),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ai?"Close Edit":"Edit Story"})]}),ai&&Ki&&y.storylineId&&f.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),xa(Dt),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ge(null),me(null),te(null),Le("unknown"),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:Xt,className:"text-xs","data-testid":"cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("select",{value:hi,onChange:ee=>re(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:rl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))}),f.jsx("select",{value:xe,onChange:ee=>Pe(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))})]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:Fe,onChange:ee=>Qe(ee.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:pr,disabled:He||!ut,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:He?"Saving...":ut?"Save Changes":"Loading..."}),Ci&&f.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),di&&f.jsx("span",{className:"text-error text-xs",children:di})]})]})]}):f.jsxs("div",{className:"flex flex-col gap-2",children:[Vi&&je&&je.total>0&&f.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[f.jsxs("span",{children:["Cuts: ",f.jsx("span",{className:"text-foreground font-medium",children:je.total})]}),f.jsxs("span",{children:["Clean: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withClean,"/",je.needClean]})]}),f.jsxs("span",{children:["Lettered: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withText,"/",je.needClean]})]}),f.jsxs("span",{children:["Uploaded: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.uploaded,"/",je.total]})]}),_&&f.jsx("button",{onClick:_,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),rn&&li&&f.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",li.total," planned",li.total>0&&f.jsxs(f.Fragment,{children:[" ","· ",li.withClean," clean"," ","· ",li.withText," lettered"," ","· ",li.exported," exported"," ","· ",li.uploaded," uploaded"]})]}),(rn||Vi)&&ma&&f.jsxs("div",{className:`${Io} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:pa===0?"Not started":"Next step"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:rn?"Genesis (Episode 1)":"Future episode"})]}),f.jsx("span",{className:"text-xs text-muted",children:ma})]}),sr&&!Vi&&L==="preview"&&f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:bt,onChange:ee=>pt(ee.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),bt&&f.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[f.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var ee;return(ee=pn.current)==null?void 0:ee.click()},onDragOver:ee=>{ee.preventDefault(),ee.stopPropagation()},onDrop:ee=>{var Ne;ee.preventDefault(),ee.stopPropagation();const Se=(Ne=ee.dataTransfer.files)==null?void 0:Ne[0];Se&&ts(Se)},children:[f.jsx("input",{ref:pn,type:"file",accept:"image/webp,image/jpeg",onChange:ha,className:"hidden"}),f.jsx("span",{className:"text-xs text-muted",children:Tt?"Uploading...":"Drop image here or click to browse"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),ot&&f.jsx("span",{className:"text-error text-xs",children:ot}),Et.map((ee,Se)=>f.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[f.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ee.url,")"]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ee.url})`),fr(Se),setTimeout(()=>fr(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:pi===Se?"Copied!":"Copy"})]})]},ee.cid))]})]}),Ki&&c!=="cartoon"&&!(L==="edit"&&M==="cuts")&&f.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[f.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image ",f.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),xa(!1),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ft.current=!0,st(null),te(null),Le("unknown"),ge(null),me(ee=>(ee&&URL.revokeObjectURL(ee),null)),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:Xt,className:"text-xs","data-testid":"prepublish-cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),f.jsx("input",{ref:fn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Un,className:"hidden","data-testid":"prepublish-cover-import-input"}),f.jsx("button",{type:"button",onClick:()=>{var ee;return(ee=fn.current)==null?void 0:ee.click()},disabled:de,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:de?"Importing…":"Import generated image (PNG ok)"}),H&&f.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),We&&f.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",We," — pick a file to override."]}),nt&&f.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[nt," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Ce==="none"&&!H&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create ",f.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),di&&f.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:di})]})]})]}),!fa&&Wu(),!fa&&ba(),!fa&&f.jsxs("div",{className:"flex items-center gap-2",children:[Ki&&c!=="cartoon"&&f.jsxs(f.Fragment,{children:[f.jsxs("select",{value:R,"data-testid":"publish-genre-select",onChange:ee=>{Y(ee.target.value),ee.target.value&&In({genre:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${R?"border-border":"border-amber-500"}`,children:[!R&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),rl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]}),f.jsxs("select",{value:C,"data-testid":"publish-language-select",onChange:ee=>{ae(ee.target.value),ee.target.value&&In({language:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${C?"border-border":"border-amber-500"}`,children:[!C&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]})]}),f.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ar.count>0){const Se=`This plot contains ${ar.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. +Create a new on-chain chapter anyway?`)||s==null||s(e,t,R,C,te)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),f.jsx("p",{className:"text-muted text-xs",children:ar?lr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":lr?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),y.indexError&&f.jsx("p",{className:"text-error text-xs",children:y.indexError})]}):(y==null?void 0:y.status)==="published"?f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-green-700",children:"Published"}),y.storylineId&&f.jsx("a",{href:(()=>{var Ne;const ee=`https://plotlink.xyz/story/${y.storylineId}`;if(!lr)return ee;const Se=y.plotIndex!=null&&y.plotIndex>0?y.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ee}/${Se}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Zi&&o&&y.storylineId&&(!y.authorAddress||y.authorAddress.toLowerCase()===o.toLowerCase())&&f.jsx("button",{onClick:()=>St(ee=>!ee),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ci?"Close Edit":"Edit Story"})]}),ci&&Zi&&y.storylineId&&f.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),xa(Mt),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ge(null),me(null),ct(null),we("unknown"),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:ts,className:"text-xs","data-testid":"cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("select",{value:fi,onChange:ee=>ne(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:nl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))}),f.jsx("select",{value:_e,onChange:ee=>Pe(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))})]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:Fe,onChange:ee=>Qe(ee.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:Ar,disabled:He||!ht,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:He?"Saving...":ht?"Save Changes":"Loading..."}),ki&&f.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),pi&&f.jsx("span",{className:"text-error text-xs",children:pi})]})]})]}):f.jsxs("div",{className:"flex flex-col gap-2",children:[Qi&&je&&je.total>0&&f.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[f.jsxs("span",{children:["Cuts: ",f.jsx("span",{className:"text-foreground font-medium",children:je.total})]}),f.jsxs("span",{children:["Clean: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withClean,"/",je.needClean]})]}),f.jsxs("span",{children:["Lettered: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withText,"/",je.needClean]})]}),f.jsxs("span",{children:["Uploaded: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.uploaded,"/",je.total]})]}),x&&f.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),an&&ei&&f.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ei.total," planned",ei.total>0&&f.jsxs(f.Fragment,{children:[" ","· ",ei.withClean," clean"," ","· ",ei.withText," lettered"," ","· ",ei.exported," exported"," ","· ",ei.uploaded," uploaded"]})]}),(an||Qi)&&pa&&f.jsxs("div",{className:`${Io} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:fa===0?"Not started":"Next step"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:an?"Genesis (Episode 1)":"Future episode"})]}),f.jsx("span",{className:"text-xs text-muted",children:pa})]}),lr&&!Qi&&D==="preview"&&f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:Rt,onChange:ee=>_t(ee.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Rt&&f.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[f.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var ee;return(ee=Tn.current)==null?void 0:ee.click()},onDragOver:ee=>{ee.preventDefault(),ee.stopPropagation()},onDrop:ee=>{var Ne;ee.preventDefault(),ee.stopPropagation();const Se=(Ne=ee.dataTransfer.files)==null?void 0:Ne[0];Se&&gn(Se)},children:[f.jsx("input",{ref:Tn,type:"file",accept:"image/webp,image/jpeg",onChange:dl,className:"hidden"}),f.jsx("span",{className:"text-xs text-muted",children:Je?"Uploading...":"Drop image here or click to browse"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),at&&f.jsx("span",{className:"text-error text-xs",children:at}),Xe.map((ee,Se)=>f.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[f.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ee.url,")"]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ee.url})`),gi(Se),setTimeout(()=>gi(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:qt===Se?"Copied!":"Copy"})]})]},ee.cid))]})]}),Zi&&c!=="cartoon"&&!(D==="edit"&&L==="cuts")&&f.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[f.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image ",f.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),xa(!1),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ze.current=!0,st(null),ct(null),we("unknown"),ge(null),me(ee=>(ee&&URL.revokeObjectURL(ee),null)),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:ts,className:"text-xs","data-testid":"prepublish-cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),f.jsx("input",{ref:mn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Zt,className:"hidden","data-testid":"prepublish-cover-import-input"}),f.jsx("button",{type:"button",onClick:()=>{var ee;return(ee=mn.current)==null?void 0:ee.click()},disabled:de,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:de?"Importing…":"Import generated image (PNG ok)"}),H&&f.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),We&&f.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",We," — pick a file to override."]}),nt&&f.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[nt," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&ae==="none"&&!H&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create ",f.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),pi&&f.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:pi})]})]})]}),!da&&Wu(),!da&&_a(),!da&&f.jsxs("div",{className:"flex items-center gap-2",children:[Zi&&c!=="cartoon"&&f.jsxs(f.Fragment,{children:[f.jsxs("select",{value:R,"data-testid":"publish-genre-select",onChange:ee=>{Y(ee.target.value),ee.target.value&&Yt({genre:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${R?"border-border":"border-amber-500"}`,children:[!R&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),nl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]}),f.jsxs("select",{value:C,"data-testid":"publish-language-select",onChange:ee=>{se(ee.target.value),ee.target.value&&Yt({language:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${C?"border-border":"border-amber-500"}`,children:[!C&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]})]}),f.jsx("button",{onClick:async()=>{if(!e||!t)return;if(or.count>0){const Se=`This plot contains ${or.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. Please verify illustrations appear correctly in Preview before continuing. -Publish now?`;if(!window.confirm(Se))return}const ee=Ki?H:null;ee?await(s==null?void 0:s(e,t,R,C,ie,ee))&&(ft.current=!0,st(null),te(null),Le("unknown"),ge(null),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Gt.current&&(Gt.current.value="")):s==null||s(e,t,R,C,ie)},disabled:!!a||is||pl||Po||Ki&&(!R||!C)||Vi&&F!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Ki&&c==="cartoon"&&(!R||!C)&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Ki&&c!=="cartoon"&&!R&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ki&&c!=="cartoon"&&R&&!C&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),is&&f.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Vi&&F==="error"&&f.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Vi&&F==="planning"&&f.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Vi&&F==="awaiting-upload"&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",be," of ",Ee," still need an uploaded image"]})]}),fa&&f.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),ar.warnings.length>0&&f.jsx("div",{className:"flex flex-col gap-0.5",children:ar.warnings.map((ee,Se)=>f.jsx("span",{className:"text-amber-600 text-xs",children:ee},Se))}),Ki&&c!=="cartoon"&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:ie,onChange:ee=>{oe(ee.target.checked),In({isNsfw:ee.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),ie&&f.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function pD({storyName:e,authFetch:t,onOpenFile:i,refreshKey:s=0}){const[a,o]=w.useState(null),[c,h]=w.useState(!0);return w.useEffect(()=>{let p=!1;return(async()=>{h(!0);try{const x=await t(`/api/stories/${e}/progress`),_=x.ok?await x.json():null;p||(o(_),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!a||!a.metadata||!Array.isArray(a.episodes)?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?f.jsx(SD,{progress:a,storyName:e,onOpenFile:i}):f.jsx(kD,{progress:a,storyName:e,onOpenFile:i})}function uu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return f.jsxs("span",{className:"text-[11px]",children:[f.jsxs("span",{className:"text-muted",children:[e,": "]}),f.jsx("span",{className:`font-medium ${s}`,children:t})]})}function WS({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return f.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),f.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),f.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[f.jsx(uu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),f.jsx(uu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&f.jsx(uu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&f.jsx(uu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const GS={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Mu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},YS={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},mD={done:"✓",current:"◓",todo:"○"},gD={done:"text-green-700",current:"text-accent",todo:"text-muted"};function KS({item:e}){return f.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[f.jsx("span",{className:`${gD[e.status]} flex-shrink-0`,"aria-hidden":!0,children:mD[e.status]}),f.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&f.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function fy({index:e,title:t,status:i,items:s,fileName:a,openFile:o,cta:c}){const h=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[i]}`,"aria-hidden":!0,children:GS[i]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[i]} flex-shrink-0`,children:YS[i]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?f.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:h}):h,f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((p,d)=>f.jsx(KS,{item:p},d))}),c&&f.jsx("div",{className:"mt-2 ml-1","data-testid":"section-cta",children:c})]})}function _D(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function xD(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(bD(a));return s}function bD(e){return{label:e.label,status:e.status,detail:e.detail}}const vD={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function yD(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image — it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function SD({progress:e,storyName:t,onOpenFile:i}){const s=e.coach??null,a=e.metadata,o=e.setup.hasStructure,c=e.setup.hasGenesis,h=e.cover==="present",p=!a.title||!a.language||!a.genre,d=p||!h,x=e.episodes.find(M=>!M.published)??null,_=!!x&&x.state!=="ready";let b;o?c?p?b="story-info":_&&(s!=null&&s.episodeFile)?b=s.episodeFile:h?b=(s==null?void 0:s.episodeFile)??null:b="story-info":b="genesis.md":b="whitepaper";const v=s?f.jsx(qS,{coach:s,onAction:(M,X)=>{M!=="view-progress"&&X&&i(t,X)}}):null,y=f.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-accent/5 border border-accent/30 rounded text-xs","data-testid":"story-info-cta",children:[f.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-accent flex-shrink-0",children:"Story info"}),f.jsxs("span",{className:"min-w-0 flex-1 text-foreground",children:[f.jsx("span",{className:"text-muted",children:"Next: "}),f.jsx("span",{className:"font-medium",children:yD(e)})]})]}),E=M=>M!==b?null:b==="story-info"?y:v,A=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:h?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":h?null:"Missing"}],N=b==="story-info"?"current":d?"needs-action":"done",L=o?"done":b==="whitepaper"?"current":"not-started",O=e.episodes.find(M=>M.kind==="genesis")??null,J=e.episodes.filter(M=>M.kind==="plot");let $=0;return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(WS,{progress:e}),f.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),f.jsx(fy,{index:++$,title:"Define Story Info",status:N,items:A,cta:E("story-info")??void 0}),f.jsx(fy,{index:++$,title:"Story Whitepaper",status:L,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}],cta:E("whitepaper")??void 0}),O?f.jsx(Bf,{index:++$,ep:O,isActive:b===O.file,storyName:t,onOpenFile:i,cta:E(O.file)??void 0}):f.jsx(Bf,{index:++$,ep:vD,isActive:b==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i,cta:E("genesis.md")??void 0}),J.map(M=>f.jsx(Bf,{index:++$,ep:M,isActive:b===M.file,storyName:t,onOpenFile:i,cta:E(M.file)??void 0},M.file)),b===null&&v&&f.jsx("div",{className:"px-4 py-2.5 border-b border-border","data-testid":"workflow-next-episode",children:f.jsx("div",{className:"ml-1","data-testid":"section-cta",children:v})}),f.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),f.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&f.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Bf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,cta:o,openingDone:c=!0,canOpen:h=!0}){const p=_D(t,i),d=xD(t,c),x=t.title?`${t.label} · ${t.title}`:t.label,_=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[p]}`,"aria-hidden":!0,children:GS[p]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",x]}),f.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[p]} flex-shrink-0`,children:YS[p]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":p,children:[h?f.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):f.jsx("div",{"data-state":t.state,children:_}),f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:d.map((b,v)=>f.jsx(KS,{item:b},v))}),o&&f.jsx("div",{className:"mt-2 ml-1","data-testid":"section-cta",children:o})]})}const wD={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},py={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},CD={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function kD({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(WS,{progress:e}),e.nextAction&&f.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),f.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&f.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[f.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),f.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),f.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[f.jsx(my,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),f.jsx(my,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),f.jsxs("div",{className:"px-4 py-2",children:[f.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?f.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):f.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>f.jsx("li",{children:f.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[f.jsx("span",{className:`mt-0.5 ${py[o.state]}`,"aria-hidden":!0,children:wD[o.state]}),f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${py[o.state]}`,children:CD[o.state]})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),f.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function my({done:e,label:t,onClick:i}){const s=f.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),f.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?f.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):f.jsx("div",{children:s})}const ED=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function ND({storyTitle:e,active:t,onSelect:i}){return f.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[f.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[f.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),f.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),f.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:ED.map(s=>{const a=s.key===t;return f.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function TD({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[d,x]=w.useState(""),[_,b]=w.useState(""),[v,y]=w.useState(""),[E,A]=w.useState(!1),[N,L]=w.useState("cartoon"),[O,J]=w.useState("unknown"),[$,M]=w.useState(!1),[X,he]=w.useState(!1),[ye,U]=w.useState(null),[se,W]=w.useState(!1),[G,Z]=w.useState(null),[I,j]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),he(!1),U(null),(async()=>{try{const[ae,ie]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!ae.ok){C||(c(!0),a(!1));return}const oe=await ae.json(),F=ie.ok?await ie.json().catch(()=>null):null;if(C)return;p(oe.title??""),x(oe.description??""),b(bu(oe.genre)??""),y(oe.language&&Xr.find(ue=>ue.toLowerCase()===oe.language.toLowerCase())||""),A(!!oe.isNsfw),L(oe.contentType==="fiction"?"fiction":"cartoon"),J((F==null?void 0:F.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const B=w.useCallback(async()=>{M(!0),he(!1),U(null);const C={title:h.trim(),description:d.trim(),genre:_,language:v,isNsfw:E};try{const ae=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(ae.ok)he(!0),i==null||i({genre:_,language:v,isNsfw:E});else{const ie=await ae.json().catch(()=>({}));U(ie.error||"Could not save story info.")}}catch{U("Could not save story info.")}M(!1)},[e,t,h,d,_,v,E,i]),_e=w.useCallback(async C=>{var ie;const ae=(ie=C.target.files)==null?void 0:ie[0];if(z.current&&(z.current.value=""),!!ae){W(!0),U(null);try{let oe;try{oe=await qu(ae)}catch(Ee){U(Ee instanceof Error?Ee.message:"Could not import image");return}const F=oe.type==="image/jpeg"?"jpg":"webp",ue=new File([oe],`cover.${F}`,{type:oe.type}),be=new FormData;be.append("file",ue);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:be});if(!De.ok){const Ee=await De.json().catch(()=>({}));U(Ee.error||"Cover import failed.");return}J("present"),Z(Ee=>(Ee&&URL.revokeObjectURL(Ee),URL.createObjectURL(ue)))}catch{U("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var ae;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(ae=navigator.clipboard)==null||ae.writeText(C).then(()=>{j(!0)}).catch(()=>{})},[h,e]);if(s)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const R=O==="present"?"Cover set":O==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",Y=O==="present"?"text-green-700":O==="invalid"?"text-amber-700":"text-muted";return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),f.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),f.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),he(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),f.jsx("textarea",{value:d,onChange:C=>{x(C.target.value),he(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),f.jsxs("div",{className:"flex flex-wrap gap-4",children:[f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),f.jsxs("select",{value:_,onChange:C=>{b(C.target.value),he(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),rl.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),f.jsxs("select",{value:v,onChange:C=>{y(C.target.value),he(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),Xr.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),f.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:N==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),f.jsxs("div",{className:"flex items-start gap-3",children:[G&&f.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:`text-[11px] font-medium ${Y}`,"data-testid":"story-info-cover-status",children:R}),f.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:se,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:se?"Importing…":"Import cover"}),f.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:I?"Copied!":"Ask agent for cover prompt"})]}),f.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:_e,className:"hidden"})]})]})]}),f.jsxs("label",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"checkbox",checked:E,onChange:C=>{A(C.target.checked),he(!1)},"data-testid":"story-info-nsfw"}),f.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{type:"button",onClick:B,disabled:$,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:$?"Saving…":"Save Story Info"}),X&&f.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&f.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function jD({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const d=await t(`/api/stories/${e}/progress`),x=d.ok?await d.json():null;h||(a(Array.isArray(x==null?void 0:x.episodes)?x.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?f.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):f.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>f.jsx("li",{children:f.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),f.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function AD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:d=0}){var mt,Ge;const[x,_]=w.useState(null),[b,v]=w.useState(!0),[y,E]=w.useState(!1),[A,N]=w.useState(null),[L,O]=w.useState(null),[J,$]=w.useState(null),[M,X]=w.useState(null),[he,ye]=w.useState(null),U=async()=>{try{const Ae=await t(`/api/stories/${e}/cover-asset`),Ve=Ae.ok?await Ae.json():null;if(!(Ve!=null&&Ve.found)||!Ve.valid||!Ve.path)return null;const Mt=await t(`/api/stories/${e}/asset/${String(Ve.path).replace(/^assets\//,"")}`);if(!Mt.ok)return null;const zt=await Mt.blob();return new File([zt],String(Ve.path).split("/").pop()||"cover.webp",{type:Ve.type||zt.type})}catch{return null}};w.useEffect(()=>{let Ae=!1;return(async()=>{v(!0),E(!1);try{const Mt=await t(`/api/stories/${e}/progress`),zt=Mt.ok?await Mt.json():null;if(Ae)return;!zt||!Array.isArray(zt.episodes)?(E(!0),_(null)):_(zt),v(!1)}catch{Ae||(E(!0),_(null),v(!1))}})(),()=>{Ae=!0}},[e,t,d]);const se=((Ge=(mt=x==null?void 0:x.episodes)==null?void 0:mt.find(Ae=>!Ae.published))==null?void 0:Ge.file)??null,W=se==="genesis.md",G=JSON.stringify([se??"",d]),[Z,I]=w.useState(null);if(Z!==G&&(I(G),O(null),$(null),X(null),ye(null)),w.useEffect(()=>{if(!se)return;let Ae=!1;const Ve=se.replace(/\.md$/,"");return(async()=>{var Mt;try{const zt=[t(`/api/stories/${e}/${se}`),t(`/api/stories/${e}/cuts/${Ve}`)];W&&zt.push(t(`/api/stories/${e}/structure.md`));const[ai,wt,hi]=await Promise.all(zt);if(Ae)return;if(O(ai.ok?(await ai.json()).content??"":""),wt.ok){const re=await wt.json();if(Ae)return;$(Array.isArray(re.cuts)?re.cuts:[]),X(typeof re.title=="string"?re.title:null)}else $(null),X(null);ye(W&&hi&&hi.ok?((Mt=await hi.json())==null?void 0:Mt.content)??null:null)}catch{Ae||(O(""),$(null),X(null),ye(null))}})(),()=>{Ae=!0}},[se,W,e,t,d]),b)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(y||!x)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const j=x.episodes.find(Ae=>!Ae.published);if(!j)return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),f.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:x.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const z=j.cuts,B=x.cover==="present",_e=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:z&&z.total>0?"done":"todo",detail:z?`${z.total} cut${z.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:z&&z.needClean>0&&z.withClean===z.needClean?"done":"todo",detail:z?`${z.withClean} / ${z.needClean}`:null},{label:"Cuts lettered",status:z&&z.needClean>0&&z.withText===z.needClean?"done":"todo",detail:z?`${z.withText} / ${z.needClean}`:null},{label:"Final images exported",status:z&&z.total>0&&z.exported===z.total?"done":"todo",detail:z?`${z.exported} / ${z.total}`:null},{label:"Final images uploaded",status:z&&z.total>0&&z.uploaded===z.total?"done":"todo",detail:z?`${z.uploaded} / ${z.total}`:null},{label:"Cover image",status:B?"done":"todo",detail:B?null:"recommended before publishing"},{label:"Publish to PlotLink",status:j.published?"done":"todo"}],T=j.state==="ready",R=j.state==="blocked",Y=j.file==="genesis.md",C=!Y||!!c&&!!h,ae=!!o&&o===j.file,ie=L!==null,oe=ie?xm({fileName:j.file,fileContent:L??"",storySlug:e,structureContent:he,contentType:"cartoon",episodeTitle:M}):null,F=!!oe&&jo(oe,j.file),ue=!Y&&ie&&!_m({fileContent:L??"",episodeTitle:M}),be=F||ue,De=Y&&ie?mm(L??""):null,Ee=!!De&&De.blockers.length>0,Be=!Y&&ie&&J!==null?zS(L??"",J):null,je=Be&&Be.stage==="error"?Be.issues:[],we=T&&C&&(ie&&(Y||J!==null))&&!be&&!Ee&&!ae&&!!a,tt=async()=>{if(!(!we||!a)){N(null);try{const Ae=Y?await U():null;await a(e,j.file,c??"",h??"",!!p,Ae)}catch{N("Publish could not be started. Please try again.")}}};return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",j.label]}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),f.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:_e.map((Ae,Ve)=>f.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Ae.status,children:[f.jsx("span",{className:`flex-shrink-0 ${Ae.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Ae.status==="done"?"✓":"○"}),f.jsx("span",{className:Ae.status==="done"?"text-foreground":"text-muted",children:Ae.label}),Ae.detail&&f.jsxs("span",{className:"text-muted",children:["· ",Ae.detail]})]},Ve))}),oe&&f.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":F?"true":"false","data-blocked":be?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[Y?"Story title":"Episode title",":"]})," ",f.jsx("span",{className:be?"text-error font-medium":"text-foreground",children:oe})]}),F?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Y?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):ue?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",oe,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),De&&f.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":Ee?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),De.blockers.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Ae},`b-${Ve}`)),De.warnings.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Ae},`w-${Ve}`))]}),je.length>0&&f.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),PS(je).map(Ae=>f.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Ae.key}`,children:f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Ae.title})},Ae.key)),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc",children:je.map((Ae,Ve)=>f.jsx("li",{className:"font-mono break-words",children:Ae},Ve))})]})]}),f.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!B&&f.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),Y&&!C&&f.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&f.jsxs("button",{onClick:()=>i(e,j.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",j.label," to finish ",R?"and fix issues":"(letter / export / upload)"]}),f.jsx("button",{onClick:tt,disabled:!we,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:we?void 0:"Finish the remaining steps above first",children:ae?"Publishing…":`Publish ${j.label} to PlotLink`}),T?C?be||Ee?f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Ee?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):f.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:R?`Not publishable yet — ${j.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${j.summary.toLowerCase()}.`}),A&&f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:A})]}),f.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[f.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[f.jsxs("p",{children:["Episode file: ",f.jsx("span",{className:"font-mono",children:j.file})]}),f.jsxs("p",{children:["State: ",j.state," — ",j.summary]}),f.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function RD(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function MD(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?jo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=RD(i,s);return a?jo(a,t)||Lp(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function DD(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const VS="plotlink-panel-ratio",BD=.6,gy=300,Lf=224,Of=6;function LD(){try{const e=localStorage.getItem(VS);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return BD}function _y(e,t){if(t<=0)return e;const i=gy/t,s=1-gy/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function OD({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[x,_]=w.useState(0),[b,v]=w.useState(""),[y,E]=w.useState(null),[A,N]=w.useState(null),[L,O]=w.useState(LD),[J,$]=w.useState([]),[M,X]=w.useState(!1),[he,ye]=w.useState(""),[U,se]=w.useState(""),[W,G]=w.useState(""),[Z,I]=w.useState("English"),[j,z]=w.useState("normal"),[B,_e]=w.useState("claude"),[T,R]=w.useState(null),[Y,C]=w.useState(!1),[ae,ie]=w.useState({}),[oe,F]=w.useState({}),[ue,be]=w.useState(new Set),[De,Ee]=w.useState(new Set),[Be,je]=w.useState({}),[Ze,we]=w.useState({}),[tt,mt]=w.useState({}),[Ge,Ae]=w.useState({}),[Ve,Mt]=w.useState({}),[zt,ai]=w.useState({}),wt=w.useRef(new Map),hi=w.useRef(new Map),re=w.useRef(new Map),xe=w.useRef(new Map),Pe=w.useRef(new Set),Fe=w.useRef(null),Qe=w.useRef(null),H=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(te=>te.ok?te.json():null).then(te=>{te!=null&&te.address&&N(te.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(te=>te.ok?te.json():null).then(te=>{te&&R(te)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(VS,String(L))}catch{}},[L]),w.useEffect(()=>{const te=()=>{if(!Qe.current)return;const Ce=Qe.current.getBoundingClientRect().width-Lf-Of;O(Le=>_y(Le,Ce))};return window.addEventListener("resize",te),te(),()=>window.removeEventListener("resize",te)},[]);const ge=w.useCallback(()=>{ye(""),se(""),G(""),z("normal"),_e("claude"),X(!0)},[]),Te=w.useCallback(async(te,Ce,Le,ft)=>{const bt=he.trim();if(!bt)return;const pt=te==="cartoon"?"codex":ft;try{const Tt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:bt,description:U.trim()||void 0,language:Ce,genre:W||void 0,contentType:te,agentMode:Le,agentProvider:pt})});if(!Tt.ok)return;const Je=await Tt.json();X(!1),je(ot=>({...ot,[Je.name]:te})),we(ot=>({...ot,[Je.name]:Ce})),W&&mt(ot=>({...ot,[Je.name]:W})),F(ot=>({...ot,[Je.name]:pt})),Le==="bypass"&&ie(ot=>({...ot,[Je.name]:!0})),s(Je.name),o(null)}catch{}},[t,he,U,W]);w.useEffect(()=>{if(J.length===0)return;const te=setInterval(async()=>{try{const Ce=await t("/api/stories");if(!Ce.ok)return;const Le=await Ce.json(),ft=new Set(Le.stories.filter(bt=>bt.name!=="_example").map(bt=>bt.name));for(const bt of ft)if(!Pe.current.has(bt)&&J.length>0){const pt=J[0],Tt=wt.current.get(pt)||"fiction",Je=hi.current.get(pt)||"English",ot=re.current.get(pt)||"normal",Xe=xe.current.get(pt)||"claude";let Et=!1;Fe.current&&(Et=await Fe.current(pt,bt,{contentType:Tt,language:Je,agentMode:ot,agentProvider:Xe}).catch(()=>!1)),Et&&($($t=>$t.slice(1)),wt.current.delete(pt),hi.current.delete(pt),re.current.delete(pt),xe.current.delete(pt),ot==="bypass"&&ie($t=>{const pi={...$t,[bt]:!0};return delete pi[pt],pi}),F($t=>{const pi={...$t,[bt]:Xe};return delete pi[pt],pi}),t(`/api/stories/${bt}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Tt,language:Je,agentMode:ot,agentProvider:Xe})}).catch(()=>{})),s(bt),o(null)}Pe.current=ft}catch{}},3e3);return()=>clearInterval(te)},[t,J]),w.useEffect(()=>{t("/api/stories").then(te=>{if(te.ok)return te.json()}).then(te=>{te!=null&&te.stories&&(Pe.current=new Set(te.stories.filter(Ce=>Ce.name!=="_example").map(Ce=>Ce.name)))}).catch(()=>{})},[t]);const me=w.useCallback((te,Ce)=>{s(te),o(Ce),h(null)},[]),He=w.useRef(null),Oe=w.useCallback(async te=>{var Ce,Le,ft,bt;He.current=te,s(te),o(null),h(null);try{const pt=await t(`/api/stories/${te}`);if(pt.ok&&He.current===te){const Tt=await pt.json();if(Tt.contentType==="cartoon")return;const Je=Tt.files||[],Xe=((Ce=Je.map(Et=>{var $t;return{file:Et.file,num:($t=Et.file.match(/^plot-(\d+)\.md$/))==null?void 0:$t[1]}}).filter(Et=>Et.num!=null).sort((Et,$t)=>parseInt($t.num)-parseInt(Et.num))[0])==null?void 0:Ce.file)??((Le=Je.find(Et=>Et.file==="genesis.md"))==null?void 0:Le.file)??((ft=Je.find(Et=>Et.file==="structure.md"))==null?void 0:ft.file)??((bt=Je[0])==null?void 0:bt.file);Xe&&He.current===te&&o(Xe)}}catch{}},[t]),ut=w.useCallback(te=>{te.preventDefault(),H.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const Ce=ft=>{if(!H.current||!Qe.current)return;const bt=Qe.current.getBoundingClientRect(),pt=bt.width-Lf-Of,Tt=ft.clientX-bt.left-Lf;O(_y(Tt/pt,pt))},Le=()=>{H.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",Ce),window.removeEventListener("mouseup",Le)};window.addEventListener("mousemove",Ce),window.addEventListener("mouseup",Le)},[]),it=w.useCallback(async(te,Ce,Le,ft,bt,pt)=>{var Xe;d(Ce),v("Reading file..."),E(null);let Tt=!1,Je=null,ot=!1;try{const Et=await t(`/api/stories/${te}/${Ce}`);if(!Et.ok)throw new Error("Failed to read file");const $t=await Et.json(),pi=Be[te];let fr=null,pn=null;if(Ce==="genesis.md")try{const ct=await t(`/api/stories/${te}/structure.md`);ct.ok&&(fr=(await ct.json()).content??null)}catch{}else if(pi==="cartoon"&&Ce.match(/^plot-\d+\.md$/))try{const ct=await t(`/api/stories/${te}/cuts/${Ce.replace(/\.md$/,"")}`);ct.ok&&(pn=(await ct.json()).title??null)}catch{}const jr=xm({fileName:Ce,fileContent:$t.content,storySlug:te,structureContent:fr,contentType:pi,episodeTitle:pn});if(pi==="cartoon"&&jo(jr,Ce))return v(Ce==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{d(null),v("")},6e3),!1;if(pi==="cartoon"&&Ce.match(/^plot-\d+\.md$/)&&!_m({fileContent:$t.content,episodeTitle:pn}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{d(null),v("")},6e3),!1;if(pi==="cartoon"&&Ce==="genesis.md"){const ct=mm($t.content).blockers;if(ct.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ct[0]}`),setTimeout(()=>{d(null),v("")},6e3),!1}let mi;if(Ce.match(/^plot-\d+\.md$/)){if(sD($t)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{d(null),v("")},6e3);return}try{const ct=await t(`/api/stories/${te}`);if(ct.ok){const rr=(await ct.json()).files.find(tn=>tn.file==="genesis.md"&&tn.storylineId);mi=rr==null?void 0:rr.storylineId}}catch{}if(!mi)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{d(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ct=await t("/api/publish/preflight");if(ct.ok){const In=await ct.json();if(lD(In))return E(oD(In)),d(null),v(""),!1}}catch{}v("Publishing...");const li=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:te,fileName:Ce,title:jr,content:$t.content,genre:Le,language:ft,isNsfw:bt,storylineId:mi,...dy(Be,te,mi)?{contentType:dy(Be,te,mi)}:{}})});if(!li.ok){const ct=await li.json();throw new Error(ct.error||"Publish failed")}const Pn=(Xe=li.body)==null?void 0:Xe.getReader(),nr=new TextDecoder;if(Pn)for(;;){const{done:ct,value:In}=await Pn.read();if(ct)break;const tn=nr.decode(In).split(` -`).filter(Hn=>Hn.startsWith("data: "));for(const Hn of tn)try{const Xt=JSON.parse(Hn.slice(6));if(Xt.step&&v(Xt.message||Xt.step),Xt.step==="done"&&Xt.txHash){if(ot=!0,await t(`/api/stories/${te}/${Ce}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Xt.txHash,storylineId:Xt.storylineId,plotIndex:Xt.plotIndex,contentCid:Xt.contentCid,gasCost:Xt.gasCost,indexError:Xt.indexError,authorAddress:A})}),_(Un=>Un+1),pt&&Ce==="genesis.md"&&Xt.storylineId){v("Uploading cover...");let Un=null;try{Un=await tD(t,Xt.storylineId,pt)}catch{}Un||(Tt=!0)}if(pi==="cartoon"&&Xt.storylineId)try{const Un=Ce!=="genesis.md",ts=`storylineId=${Xt.storylineId}`+(Un&&Xt.plotIndex!=null?`&plotIndex=${Xt.plotIndex}`:""),ha=await t(`/api/publish/public-title?${ts}`);if(ha.ok){const pr=await ha.json(),Ar=Un?{plots:pr.plotTitle!=null?[{plotIndex:Xt.plotIndex,title:pr.plotTitle}]:[]}:{title:pr.storylineTitle},nn=MD({fileName:Ce,detail:Ar,plotIndex:Xt.plotIndex});nn.ok||(Je=DD(nn))}}catch{}}}catch{}}Je&&E(Je),v(Tt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Et){const $t=Et instanceof Error?Et.message:"Publish failed";v(`Error: ${$t}`)}finally{setTimeout(()=>{d(null),v("")},3e3)}return ot&&!Tt},[t,Be,A]),Dt=w.useCallback(te=>{te.startsWith("_new_")&&($(Ce=>Ce.filter(Le=>Le!==te)),wt.current.delete(te),hi.current.delete(te),re.current.delete(te),xe.current.delete(te),ie(Ce=>{if(!(te in Ce))return Ce;const Le={...Ce};return delete Le[te],Le}),F(Ce=>{if(!(te in Ce))return Ce;const Le={...Ce};return delete Le[te],Le}))},[]);w.useEffect(()=>{const te=Le=>{be(new Set(Le.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Ee(new Set(Le.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const ft={},bt={},pt={},Tt={},Je={},ot={};for(const Xe of Le)ft[Xe.name]=Xe.contentType||"fiction",bt[Xe.name]=Xe.language,pt[Xe.name]=Xe.genre,Tt[Xe.name]=Xe.isNsfw,Je[Xe.name]=Xe.agentProvider,Xe.title&&(ot[Xe.name]=Xe.title);je(ft),we(bt),mt(pt),Ae(Tt),ai(Je),Mt(ot)};t("/api/stories").then(Le=>Le.ok?Le.json():null).then(Le=>{Le!=null&&Le.stories&&te(Le.stories)}).catch(()=>{});const Ce=setInterval(async()=>{try{const Le=await t("/api/stories");if(Le.ok){const ft=await Le.json();te(ft.stories)}}catch{}},5e3);return()=>clearInterval(Ce)},[t]);const Bt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",di=!!T&&!Bt,kt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Ci=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const te=i;if((await t(`/api/stories/${te}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ai(Le=>({...Le,[te]:"codex"})),F(Le=>({...Le,[te]:"codex"}));try{const Le=await t("/api/stories");if(Le.ok){const ft=await Le.json();if(ft!=null&&ft.stories){const bt={};for(const pt of ft.stories)bt[pt.name]=pt.agentProvider;ai(bt)}}}catch{}}},[t,i]),fi=w.useCallback(te=>{i===te&&(s(null),o(null))},[i]),Gt=i?oe[i]??zt[i]:void 0,fn=Mf(i,Be,wt.current),de=aD(fn,Gt,i),Re=!!i&&fn==="cartoon",We=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",st=w.useCallback(te=>{const Ce=i;if(Ce)switch(te){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":me(Ce,"structure.md");break;case"genesis":me(Ce,"genesis.md");break;case"publish":h("publish");break}},[i,me]),nt=w.useCallback(te=>{i&&(te.genre!==void 0&&mt(Ce=>({...Ce,[i]:te.genre||void 0})),te.language!==void 0&&we(Ce=>({...Ce,[i]:te.language||void 0})),te.isNsfw!==void 0&&Ae(Ce=>({...Ce,[i]:te.isNsfw})))},[i]);return f.jsxs("div",{ref:Qe,className:"h-[calc(100vh-3.5rem)] flex",children:[f.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:f.jsx(_C,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:me,onNewStory:ge,untitledSessions:J})}),f.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${L} 0 0`},children:f.jsx(FE,{token:e,storyName:i,authFetch:t,onSelectStory:Oe,onDestroySession:Dt,onArchiveStory:fi,confirmedStories:ue,renameRef:Fe,bypassStories:ae,agentProviders:oe,readiness:T,contentType:Mf(i,Be,wt.current),needsProviderRepair:de,onRepairProvider:Ci})}),f.jsx("div",{onMouseDown:ut,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Of,cursor:"col-resize",background:"var(--border)"},children:f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),f.jsxs("div",{className:"min-w-0 flex flex-col",style:{flex:`${1-L} 0 0`},children:[Re&&i&&f.jsx(ND,{storyTitle:Ve[i]||i,active:We,onSelect:st}),Re&&c==="story-info"&&i?f.jsx(TD,{storyName:i,authFetch:t,onSaved:nt}):Re&&c==="episodes"&&i?f.jsx(jD,{storyName:i,authFetch:t,onOpenFile:me}):Re&&c==="publish"&&i?f.jsx(AD,{storyName:i,authFetch:t,onOpenFile:me,onOpenStoryInfo:()=>h("story-info"),onPublish:it,publishingFile:p,genre:tt[i],language:Ze[i],isNsfw:Ge[i],refreshKey:x}):i&&!a?f.jsx(pD,{storyName:i,authFetch:t,onOpenFile:me}):f.jsx(fD,{storyName:i,fileName:a,authFetch:t,onPublish:it,publishingFile:p,walletAddress:A,contentType:Mf(i,Be,wt.current)||"fiction",language:i?Ze[i]:void 0,genre:i?tt[i]:void 0,isNsfw:i?Ge[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:te=>i&&me(i,te),onViewPublish:()=>h("publish")}),b&&f.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),y&&f.jsxs("div",{className:"px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[f.jsx("span",{children:y}),f.jsx("button",{type:"button",onClick:()=>E(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),M&&f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[f.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",f.jsx("span",{className:"text-accent",children:"*"})]}),f.jsx("input",{type:"text",value:he,onChange:te=>ye(te.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),f.jsx("input",{type:"text",value:U,onChange:te=>se(te.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),f.jsxs("select",{value:W,onChange:te=>G(te.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"— Select later —"}),rl.map(te=>f.jsx("option",{value:te,children:te},te))]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),f.jsx("select",{value:Z,onChange:te=>I(te.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:Xr.map(te=>f.jsx("option",{value:te,children:te},te))})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),f.jsxs("select",{value:j,onChange:te=>z(te.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[f.jsx("option",{value:"normal",children:"Normal (approve each action)"}),f.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),j==="bypass"&&f.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),f.jsxs("select",{value:B,onChange:te=>_e(te.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[f.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),f.jsx("option",{value:"codex",children:"🎨 Codex"})]}),f.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:B==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),f.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!he.trim()&&f.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),f.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[f.jsxs("button",{onClick:()=>Te("fiction",Z,j,B),disabled:!he.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),f.jsxs("div",{className:"space-y-1",children:[f.jsxs("button",{onClick:()=>Te("cartoon",Z,j,"codex"),disabled:di||!he.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),f.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&f.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Su(T)&&f.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:zp}),T&&T.codex.installed&&!Su(T)&&T.codex.imageGeneration!=="enabled"&&f.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[f.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),f.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:kt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:Y?"Copied!":"Copy"})]})]})]})]}),f.jsx("button",{onClick:()=>X(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function zD({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const d=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),x=await d.json();if(!d.ok)throw new Error(x.error||"Wallet creation failed");h(!0)}catch(d){o(d instanceof Error?d.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),f.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[f.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),f.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&f.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),f.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"text-accent text-2xl",children:"✓"}),f.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),f.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function PD({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(d,x)=>fetch(d,{...x,headers:{...(x==null?void 0:x.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(d=>d.json()).then(d=>{d.version&&h(d.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function d(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(y=>y.name!=="_example").length)}}catch{}}d()},[e]),f.jsxs("div",{className:"flex h-screen flex-col",children:[f.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:f.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),f.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&f.jsxs("nav",{className:"flex items-center gap-4",children:[f.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),f.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),f.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),f.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),f.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),f.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&f.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),f.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[f.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),f.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[f.jsxs("li",{children:["Open the ",f.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),f.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),f.jsx("li",{children:"Review the live preview as the agent creates files"}),f.jsxs("li",{children:["Click ",f.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),f.jsxs("li",{children:["Earn 5% royalties on every trade at ",f.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),f.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),f.jsx("div",{className:"text-center",children:f.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),f.jsx(yy,{token:e})]}),i==="stories"&&f.jsx(OD,{token:e,authFetch:p}),i==="dashboard"&&f.jsx(pC,{token:e}),i==="wallet-setup"&&f.jsx(zD,{token:e,onComplete:()=>s("home")}),i==="settings"&&f.jsx(dC,{token:e,onLogout:t})]})]})}function ID(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(d=>d.json()).then(d=>s(d.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(d=>{d.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async d=>{try{const x=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),_=await x.json();return x.ok?(localStorage.setItem("ows-token",_.token),t(_.token),null):_.error||"Login failed"}catch{return"Cannot connect to server"}},h=async d=>{try{const x=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),_=await x.json();return x.ok?(localStorage.setItem("ows-token",_.token),t(_.token),s(!0),null):_.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?f.jsx("div",{className:"flex h-screen items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?f.jsx(PD,{token:e,onLogout:p}):f.jsx(uC,{onLogin:c}):f.jsx(hC,{onSetup:h})}cC.createRoot(document.getElementById("root")).render(f.jsx(tC.StrictMode,{children:f.jsx(ID,{})}));export{Dp as M,su as a,k3 as b,MM as c,N3 as d,ru as l,DS as s,I3 as t,qD as v}; +Publish now?`;if(!window.confirm(Se))return}const ee=Zi?H:null;ee?await(s==null?void 0:s(e,t,R,C,te,ee))&&(ze.current=!0,st(null),ct(null),we("unknown"),ge(null),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Gt.current&&(Gt.current.value="")):s==null||s(e,t,R,C,te)},disabled:!!a||is||pl||Po||Zi&&(!R||!C)||Qi&&$!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Zi&&c==="cartoon"&&(!R||!C)&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Zi&&c!=="cartoon"&&!R&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Zi&&c!=="cartoon"&&R&&!C&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),is&&f.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Qi&&$==="error"&&f.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Qi&&$==="planning"&&f.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Qi&&$==="awaiting-upload"&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",be," of ",Ee," still need an uploaded image"]})]}),da&&f.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),or.warnings.length>0&&f.jsx("div",{className:"flex flex-col gap-0.5",children:or.warnings.map((ee,Se)=>f.jsx("span",{className:"text-amber-600 text-xs",children:ee},Se))}),Zi&&c!=="cartoon"&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:te,onChange:ee=>{oe(ee.target.checked),Yt({isNsfw:ee.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),te&&f.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function gD(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image - it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function WS(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(d=>!d.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function xD({progress:e,onOpenStoryInfo:t}){return f.jsx("div",{className:"m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm","data-testid":"story-info-cta",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"Story info"}),f.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"story-info-next-action",children:[f.jsx("span",{className:"font-semibold",children:"Next: "}),f.jsx("span",{children:gD(e)})]})]}),f.jsx("button",{type:"button",onClick:t,disabled:!t,className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50","data-testid":"story-info-next-action-btn",children:"Next Action"})]})})}function GS({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return WS(e)==="story-info"?f.jsx(xD,{progress:e,onOpenStoryInfo:i}):f.jsx(xm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function _D({storyName:e,authFetch:t,refreshKey:i=0,onCoachAction:s,onOpenStoryInfo:a}){const[o,c]=w.useState(void 0),h=JSON.stringify([e,i]),[p,d]=w.useState(null);return p!==h&&(c(void 0),d(h)),w.useEffect(()=>{let _=!1;return t(`/api/stories/${e}/progress`).then(x=>x.ok?x.json():null).then(x=>{_||c(bD(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?f.jsx(GS,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):f.jsx(xm,{coach:null,showEmptyState:!0,onAction:s})}function bD(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function vD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,refreshKey:a=0}){const[o,c]=w.useState(null),[h,p]=w.useState(!0);return w.useEffect(()=>{let d=!1;return(async()=>{p(!0);try{const x=await t(`/api/stories/${e}/progress`),b=x.ok?await x.json():null;d||(c(b),p(!1))}catch{d||(c(null),p(!1))}})(),()=>{d=!0}},[e,t,a]),h?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!o||!o.metadata||!Array.isArray(o.episodes)?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):o.contentType==="cartoon"?f.jsx(ND,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):f.jsx(AD,{progress:o,storyName:e,onOpenFile:i})}function uu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return f.jsxs("span",{className:"text-[11px]",children:[f.jsxs("span",{className:"text-muted",children:[e,": "]}),f.jsx("span",{className:`font-medium ${s}`,children:t})]})}function YS({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return f.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),f.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),f.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[f.jsx(uu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),f.jsx(uu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&f.jsx(uu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&f.jsx(uu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const KS={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Mu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},VS={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},yD={done:"✓",current:"◓",todo:"○"},SD={done:"text-green-700",current:"text-accent",todo:"text-muted"};function XS({item:e}){return f.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[f.jsx("span",{className:`${SD[e.status]} flex-shrink-0`,"aria-hidden":!0,children:yD[e.status]}),f.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&f.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function py({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[i]}`,"aria-hidden":!0,children:KS[i]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[i]} flex-shrink-0`,children:VS[i]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?f.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:c}):c,f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>f.jsx(XS,{item:h},p))})]})}function wD(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function CD(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(kD(a));return s}function kD(e){return{label:e.label,status:e.status,detail:e.detail}}const ED={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function ND({progress:e,storyName:t,onOpenFile:i,onOpenStoryInfo:s}){const a=e.metadata,o=e.setup.hasStructure,c=e.cover==="present",p=!a.title||!a.language||!a.genre||!c,d=WS(e),_=f.jsx(GS,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,D)=>{E!=="view-progress"&&D&&i(t,D)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=d==="story-info"?"current":p?"needs-action":"done",v=o?"done":d==="whitepaper"?"current":"not-started",y=e.episodes.find(E=>E.kind==="genesis")??null,N=e.episodes.filter(E=>E.kind==="plot");let A=0;return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(YS,{progress:e}),f.jsx("div",{className:"border-b border-border","data-testid":"persistent-next-action",children:_}),f.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),f.jsx(py,{index:++A,title:"Define Story Info",status:b,items:x}),f.jsx(py,{index:++A,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),y?f.jsx(Bf,{index:++A,ep:y,isActive:d===y.file,storyName:t,onOpenFile:i}):f.jsx(Bf,{index:++A,ep:ED,isActive:d==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),N.map(E=>f.jsx(Bf,{index:++A,ep:E,isActive:d===E.file,storyName:t,onOpenFile:i},E.file)),f.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),f.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&f.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Bf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=wD(t,i),p=CD(t,o),d=t.title?`${t.label} · ${t.title}`:t.label,_=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[h]}`,"aria-hidden":!0,children:KS[h]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",d]}),f.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[h]} flex-shrink-0`,children:VS[h]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?f.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):f.jsx("div",{"data-state":t.state,children:_}),f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>f.jsx(XS,{item:x},b))})]})}const TD={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},my={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},jD={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function AD({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(YS,{progress:e}),e.nextAction&&f.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),f.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&f.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[f.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),f.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),f.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[f.jsx(gy,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),f.jsx(gy,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),f.jsxs("div",{className:"px-4 py-2",children:[f.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?f.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):f.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>f.jsx("li",{children:f.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[f.jsx("span",{className:`mt-0.5 ${my[o.state]}`,"aria-hidden":!0,children:TD[o.state]}),f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${my[o.state]}`,children:jD[o.state]})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),f.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function gy({done:e,label:t,onClick:i}){const s=f.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),f.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?f.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):f.jsx("div",{children:s})}const RD=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function MD({storyTitle:e,active:t,onSelect:i}){return f.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[f.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[f.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),f.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),f.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:RD.map(s=>{const a=s.key===t;return f.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function DD({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[d,_]=w.useState(""),[x,b]=w.useState(""),[v,y]=w.useState(""),[N,A]=w.useState(!1),[E,D]=w.useState("cartoon"),[P,J]=w.useState("unknown"),[q,L]=w.useState(!1),[Z,he]=w.useState(!1),[ye,U]=w.useState(null),[re,W]=w.useState(!1),[G,X]=w.useState(null),[I,j]=w.useState(!1),O=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),he(!1),U(null),(async()=>{try{const[se,te]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!se.ok){C||(c(!0),a(!1));return}const oe=await se.json(),$=te.ok?await te.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(bu(oe.genre)??""),y(oe.language&&Xr.find(ue=>ue.toLowerCase()===oe.language.toLowerCase())||""),A(!!oe.isNsfw),D(oe.contentType==="fiction"?"fiction":"cartoon"),J(($==null?void 0:$.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const B=w.useCallback(async()=>{L(!0),he(!1),U(null);const C={title:h.trim(),description:d.trim(),genre:x,language:v,isNsfw:N};try{const se=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(se.ok)he(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const te=await se.json().catch(()=>({}));U(te.error||"Could not save story info.")}}catch{U("Could not save story info.")}L(!1)},[e,t,h,d,x,v,N,i]),xe=w.useCallback(async C=>{var te;const se=(te=C.target.files)==null?void 0:te[0];if(O.current&&(O.current.value=""),!!se){W(!0),U(null);try{let oe;try{oe=await qu(se)}catch(Ee){U(Ee instanceof Error?Ee.message:"Could not import image");return}const $=oe.type==="image/jpeg"?"jpg":"webp",ue=new File([oe],`cover.${$}`,{type:oe.type}),be=new FormData;be.append("file",ue);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:be});if(!De.ok){const Ee=await De.json().catch(()=>({}));U(Ee.error||"Cover import failed.");return}J("present"),X(Ee=>(Ee&&URL.revokeObjectURL(Ee),URL.createObjectURL(ue)))}catch{U("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var se;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(se=navigator.clipboard)==null||se.writeText(C).then(()=>{j(!0)}).catch(()=>{})},[h,e]);if(s)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const R=P==="present"?"Cover set":P==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",Y=P==="present"?"text-green-700":P==="invalid"?"text-amber-700":"text-muted";return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),f.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),f.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),he(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),f.jsx("textarea",{value:d,onChange:C=>{_(C.target.value),he(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),f.jsxs("div",{className:"flex flex-wrap gap-4",children:[f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),f.jsxs("select",{value:x,onChange:C=>{b(C.target.value),he(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),nl.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),f.jsxs("select",{value:v,onChange:C=>{y(C.target.value),he(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),Xr.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),f.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),f.jsxs("div",{className:"flex items-start gap-3",children:[G&&f.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:`text-[11px] font-medium ${Y}`,"data-testid":"story-info-cover-status",children:R}),f.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{type:"button",onClick:()=>{var C;return(C=O.current)==null?void 0:C.click()},disabled:re,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:re?"Importing…":"Import cover"}),f.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:I?"Copied!":"Ask agent for cover prompt"})]}),f.jsx("input",{ref:O,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),f.jsxs("label",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"checkbox",checked:N,onChange:C=>{A(C.target.checked),he(!1)},"data-testid":"story-info-nsfw"}),f.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{type:"button",onClick:B,disabled:q,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:q?"Saving…":"Save Story Info"}),Z&&f.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&f.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function BD({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const d=await t(`/api/stories/${e}/progress`),_=d.ok?await d.json():null;h||(a(Array.isArray(_==null?void 0:_.episodes)?_.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?f.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):f.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>f.jsx("li",{children:f.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),f.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function LD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:d=0}){var pt,Ge;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[y,N]=w.useState(!1),[A,E]=w.useState(null),[D,P]=w.useState(null),[J,q]=w.useState(null),[L,Z]=w.useState(null),[he,ye]=w.useState(null),U=async()=>{try{const Ae=await t(`/api/stories/${e}/cover-asset`),Ve=Ae.ok?await Ae.json():null;if(!(Ve!=null&&Ve.found)||!Ve.valid||!Ve.path)return null;const At=await t(`/api/stories/${e}/asset/${String(Ve.path).replace(/^assets\//,"")}`);if(!At.ok)return null;const Ot=await At.blob();return new File([Ot],String(Ve.path).split("/").pop()||"cover.webp",{type:Ve.type||Ot.type})}catch{return null}};w.useEffect(()=>{let Ae=!1;return(async()=>{v(!0),N(!1);try{const At=await t(`/api/stories/${e}/progress`),Ot=At.ok?await At.json():null;if(Ae)return;!Ot||!Array.isArray(Ot.episodes)?(N(!0),x(null)):x(Ot),v(!1)}catch{Ae||(N(!0),x(null),v(!1))}})(),()=>{Ae=!0}},[e,t,d]);const re=((Ge=(pt=_==null?void 0:_.episodes)==null?void 0:pt.find(Ae=>!Ae.published))==null?void 0:Ge.file)??null,W=re==="genesis.md",G=JSON.stringify([re??"",d]),[X,I]=w.useState(null);if(X!==G&&(I(G),P(null),q(null),Z(null),ye(null)),w.useEffect(()=>{if(!re)return;let Ae=!1;const Ve=re.replace(/\.md$/,"");return(async()=>{var At;try{const Ot=[t(`/api/stories/${e}/${re}`),t(`/api/stories/${e}/cuts/${Ve}`)];W&&Ot.push(t(`/api/stories/${e}/structure.md`));const[ci,St,fi]=await Promise.all(Ot);if(Ae)return;if(P(ci.ok?(await ci.json()).content??"":""),St.ok){const ne=await St.json();if(Ae)return;q(Array.isArray(ne.cuts)?ne.cuts:[]),Z(typeof ne.title=="string"?ne.title:null)}else q(null),Z(null);ye(W&&fi&&fi.ok?((At=await fi.json())==null?void 0:At.content)??null:null)}catch{Ae||(P(""),q(null),Z(null),ye(null))}})(),()=>{Ae=!0}},[re,W,e,t,d]),b)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(y||!_)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const j=_.episodes.find(Ae=>!Ae.published);if(!j)return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),f.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const O=j.cuts,B=_.cover==="present",xe=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:O&&O.total>0?"done":"todo",detail:O?`${O.total} cut${O.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:O&&O.needClean>0&&O.withClean===O.needClean?"done":"todo",detail:O?`${O.withClean} / ${O.needClean}`:null},{label:"Cuts lettered",status:O&&O.needClean>0&&O.withText===O.needClean?"done":"todo",detail:O?`${O.withText} / ${O.needClean}`:null},{label:"Final images exported",status:O&&O.total>0&&O.exported===O.total?"done":"todo",detail:O?`${O.exported} / ${O.total}`:null},{label:"Final images uploaded",status:O&&O.total>0&&O.uploaded===O.total?"done":"todo",detail:O?`${O.uploaded} / ${O.total}`:null},{label:"Cover image",status:B?"done":"todo",detail:B?null:"recommended before publishing"},{label:"Publish to PlotLink",status:j.published?"done":"todo"}],T=j.state==="ready",R=j.state==="blocked",Y=j.file==="genesis.md",C=!Y||!!c&&!!h,se=!!o&&o===j.file,te=D!==null,oe=te?bm({fileName:j.file,fileContent:D??"",storySlug:e,structureContent:he,contentType:"cartoon",episodeTitle:L}):null,$=!!oe&&jo(oe,j.file),ue=!Y&&te&&!_m({fileContent:D??"",episodeTitle:L}),be=$||ue,De=Y&&te?mm(D??""):null,Ee=!!De&&De.blockers.length>0,Be=!Y&&te&&J!==null?PS(D??"",J):null,je=Be&&Be.stage==="error"?Be.issues:[],Ce=T&&C&&(te&&(Y||J!==null))&&!be&&!Ee&&!se&&!!a,tt=async()=>{if(!(!Ce||!a)){E(null);try{const Ae=Y?await U():null;await a(e,j.file,c??"",h??"",!!p,Ae)}catch{E("Publish could not be started. Please try again.")}}};return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",j.label]}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),f.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Ae,Ve)=>f.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Ae.status,children:[f.jsx("span",{className:`flex-shrink-0 ${Ae.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Ae.status==="done"?"✓":"○"}),f.jsx("span",{className:Ae.status==="done"?"text-foreground":"text-muted",children:Ae.label}),Ae.detail&&f.jsxs("span",{className:"text-muted",children:["· ",Ae.detail]})]},Ve))}),oe&&f.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":$?"true":"false","data-blocked":be?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[Y?"Story title":"Episode title",":"]})," ",f.jsx("span",{className:be?"text-error font-medium":"text-foreground",children:oe})]}),$?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Y?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):ue?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",oe,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),De&&f.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":Ee?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),De.blockers.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Ae},`b-${Ve}`)),De.warnings.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Ae},`w-${Ve}`))]}),je.length>0&&f.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),IS(je).map(Ae=>f.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Ae.key}`,children:f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Ae.title})},Ae.key)),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc",children:je.map((Ae,Ve)=>f.jsx("li",{className:"font-mono break-words",children:Ae},Ve))})]})]}),f.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!B&&f.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),Y&&!C&&f.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&f.jsxs("button",{onClick:()=>i(e,j.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",j.label," to finish ",R?"and fix issues":"(letter / export / upload)"]}),f.jsx("button",{onClick:tt,disabled:!Ce,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:Ce?void 0:"Finish the remaining steps above first",children:se?"Publishing…":`Publish ${j.label} to PlotLink`}),T?C?be||Ee?f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Ee?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):f.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:R?`Not publishable yet — ${j.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${j.summary.toLowerCase()}.`}),A&&f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:A})]}),f.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[f.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[f.jsxs("p",{children:["Episode file: ",f.jsx("span",{className:"font-mono",children:j.file})]}),f.jsxs("p",{children:["State: ",j.state," — ",j.summary]}),f.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function OD(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function zD(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?jo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=OD(i,s);return a?jo(a,t)||Lp(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function PD(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const ZS="plotlink-panel-ratio",ID=.6,xy=300,Lf=224,Of=6;function HD(){try{const e=localStorage.getItem(ZS);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return ID}function _y(e,t){if(t<=0)return e;const i=xy/t,s=1-xy/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function UD({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[y,N]=w.useState(null),[A,E]=w.useState(null),[D,P]=w.useState(HD),[J,q]=w.useState([]),[L,Z]=w.useState(!1),[he,ye]=w.useState(""),[U,re]=w.useState(""),[W,G]=w.useState(""),[X,I]=w.useState("English"),[j,O]=w.useState("normal"),[B,xe]=w.useState("claude"),[T,R]=w.useState(null),[Y,C]=w.useState(!1),[se,te]=w.useState({}),[oe,$]=w.useState({}),[ue,be]=w.useState(new Set),[De,Ee]=w.useState(new Set),[Be,je]=w.useState({}),[Ze,Ce]=w.useState({}),[tt,pt]=w.useState({}),[Ge,Ae]=w.useState({}),[Ve,At]=w.useState({}),[Ot,ci]=w.useState({}),St=w.useRef(new Map),fi=w.useRef(new Map),ne=w.useRef(new Map),_e=w.useRef(new Map),Pe=w.useRef(new Set),Fe=w.useRef(null),Qe=w.useRef(null),H=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(ae=>ae.ok?ae.json():null).then(ae=>{ae!=null&&ae.address&&E(ae.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&R(ae)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(ZS,String(D))}catch{}},[D]),w.useEffect(()=>{const ae=()=>{if(!Qe.current)return;const we=Qe.current.getBoundingClientRect().width-Lf-Of;P(ze=>_y(ze,we))};return window.addEventListener("resize",ae),ae(),()=>window.removeEventListener("resize",ae)},[]);const ge=w.useCallback(()=>{ye(""),re(""),G(""),O("normal"),xe("claude"),Z(!0)},[]),Te=w.useCallback(async(ae,we,ze,Rt)=>{const _t=he.trim();if(!_t)return;const Je=ae==="cartoon"?"codex":Rt;try{const ut=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_t,description:U.trim()||void 0,language:we,genre:W||void 0,contentType:ae,agentMode:ze,agentProvider:Je})});if(!ut.ok)return;const at=await ut.json();Z(!1),je(wt=>({...wt,[at.name]:ae})),Ce(wt=>({...wt,[at.name]:we})),W&&pt(wt=>({...wt,[at.name]:W})),$(wt=>({...wt,[at.name]:Je})),ze==="bypass"&&te(wt=>({...wt,[at.name]:!0})),s(at.name),o(null)}catch{}},[t,he,U,W]);w.useEffect(()=>{if(J.length===0)return;const ae=setInterval(async()=>{try{const we=await t("/api/stories");if(!we.ok)return;const ze=await we.json(),Rt=new Set(ze.stories.filter(_t=>_t.name!=="_example").map(_t=>_t.name));for(const _t of Rt)if(!Pe.current.has(_t)&&J.length>0){const Je=J[0],ut=St.current.get(Je)||"fiction",at=fi.current.get(Je)||"English",wt=ne.current.get(Je)||"normal",Xe=_e.current.get(Je)||"claude";let zt=!1;Fe.current&&(zt=await Fe.current(Je,_t,{contentType:ut,language:at,agentMode:wt,agentProvider:Xe}).catch(()=>!1)),zt&&(q(qt=>qt.slice(1)),St.current.delete(Je),fi.current.delete(Je),ne.current.delete(Je),_e.current.delete(Je),wt==="bypass"&&te(qt=>{const gi={...qt,[_t]:!0};return delete gi[Je],gi}),$(qt=>{const gi={...qt,[_t]:Xe};return delete gi[Je],gi}),t(`/api/stories/${_t}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:ut,language:at,agentMode:wt,agentProvider:Xe})}).catch(()=>{})),s(_t),o(null)}Pe.current=Rt}catch{}},3e3);return()=>clearInterval(ae)},[t,J]),w.useEffect(()=>{t("/api/stories").then(ae=>{if(ae.ok)return ae.json()}).then(ae=>{ae!=null&&ae.stories&&(Pe.current=new Set(ae.stories.filter(we=>we.name!=="_example").map(we=>we.name)))}).catch(()=>{})},[t]);const me=w.useCallback((ae,we)=>{s(ae),o(we),h(null)},[]),He=w.useRef(null),Le=w.useCallback(async ae=>{var we,ze,Rt,_t;He.current=ae,s(ae),o(null),h(null);try{const Je=await t(`/api/stories/${ae}`);if(Je.ok&&He.current===ae){const ut=await Je.json();if(ut.contentType==="cartoon")return;const at=ut.files||[],Xe=((we=at.map(zt=>{var qt;return{file:zt.file,num:(qt=zt.file.match(/^plot-(\d+)\.md$/))==null?void 0:qt[1]}}).filter(zt=>zt.num!=null).sort((zt,qt)=>parseInt(qt.num)-parseInt(zt.num))[0])==null?void 0:we.file)??((ze=at.find(zt=>zt.file==="genesis.md"))==null?void 0:ze.file)??((Rt=at.find(zt=>zt.file==="structure.md"))==null?void 0:Rt.file)??((_t=at[0])==null?void 0:_t.file);Xe&&He.current===ae&&o(Xe)}}catch{}},[t]),ht=w.useCallback(ae=>{ae.preventDefault(),H.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const we=Rt=>{if(!H.current||!Qe.current)return;const _t=Qe.current.getBoundingClientRect(),Je=_t.width-Lf-Of,ut=Rt.clientX-_t.left-Lf;P(_y(ut/Je,Je))},ze=()=>{H.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",we),window.removeEventListener("mouseup",ze)};window.addEventListener("mousemove",we),window.addEventListener("mouseup",ze)},[]),it=w.useCallback(async(ae,we,ze,Rt,_t,Je)=>{var Xe;d(we),v("Reading file..."),N(null);let ut=!1,at=null,wt=!1;try{const zt=await t(`/api/stories/${ae}/${we}`);if(!zt.ok)throw new Error("Failed to read file");const qt=await zt.json(),gi=Be[ae];let Tn=null,mr=null;if(we==="genesis.md")try{const Yt=await t(`/api/stories/${ae}/structure.md`);Yt.ok&&(Tn=(await Yt.json()).content??null)}catch{}else if(gi==="cartoon"&&we.match(/^plot-\d+\.md$/))try{const Yt=await t(`/api/stories/${ae}/cuts/${we.replace(/\.md$/,"")}`);Yt.ok&&(mr=(await Yt.json()).title??null)}catch{}const $i=bm({fileName:we,fileContent:qt.content,storySlug:ae,structureContent:Tn,contentType:gi,episodeTitle:mr});if(gi==="cartoon"&&jo($i,we))return v(we==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{d(null),v("")},6e3),!1;if(gi==="cartoon"&&we.match(/^plot-\d+\.md$/)&&!_m({fileContent:qt.content,episodeTitle:mr}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{d(null),v("")},6e3),!1;if(gi==="cartoon"&&we==="genesis.md"){const Yt=mm(qt.content).blockers;if(Yt.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Yt[0]}`),setTimeout(()=>{d(null),v("")},6e3),!1}let ei;if(we.match(/^plot-\d+\.md$/)){if(lD(qt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{d(null),v("")},6e3);return}try{const Yt=await t(`/api/stories/${ae}`);if(Yt.ok){const sn=(await Yt.json()).files.find(An=>An.file==="genesis.md"&&An.storylineId);ei=sn==null?void 0:sn.storylineId}}catch{}if(!ei)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{d(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Yt=await t("/api/publish/preflight");if(Yt.ok){const qn=await Yt.json();if(cD(qn))return N(uD(qn)),d(null),v(""),!1}}catch{}v("Publishing...");const jn=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:ae,fileName:we,title:$i,content:qt.content,genre:ze,language:Rt,isNsfw:_t,storylineId:ei,...fy(Be,ae,ei)?{contentType:fy(Be,ae,ei)}:{}})});if(!jn.ok){const Yt=await jn.json();throw new Error(Yt.error||"Publish failed")}const Fn=(Xe=jn.body)==null?void 0:Xe.getReader(),ti=new TextDecoder;if(Fn)for(;;){const{done:Yt,value:qn}=await Fn.read();if(Yt)break;const An=ti.decode(qn).split(` +`).filter(ts=>ts.startsWith("data: "));for(const ts of An)try{const Zt=JSON.parse(ts.slice(6));if(Zt.step&&v(Zt.message||Zt.step),Zt.step==="done"&&Zt.txHash){if(wt=!0,await t(`/api/stories/${ae}/${we}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Zt.txHash,storylineId:Zt.storylineId,plotIndex:Zt.plotIndex,contentCid:Zt.contentCid,gasCost:Zt.gasCost,indexError:Zt.indexError,authorAddress:A})}),x(gn=>gn+1),Je&&we==="genesis.md"&&Zt.storylineId){v("Uploading cover...");let gn=null;try{gn=await nD(t,Zt.storylineId,Je)}catch{}gn||(ut=!0)}if(gi==="cartoon"&&Zt.storylineId)try{const gn=we!=="genesis.md",dl=`storylineId=${Zt.storylineId}`+(gn&&Zt.plotIndex!=null?`&plotIndex=${Zt.plotIndex}`:""),Ar=await t(`/api/publish/public-title?${dl}`);if(Ar.ok){const ar=await Ar.json(),xn=gn?{plots:ar.plotTitle!=null?[{plotIndex:Zt.plotIndex,title:ar.plotTitle}]:[]}:{title:ar.storylineTitle},Xi=zD({fileName:we,detail:xn,plotIndex:Zt.plotIndex});Xi.ok||(at=PD(Xi))}}catch{}}}catch{}}at&&N(at),v(ut?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(zt){const qt=zt instanceof Error?zt.message:"Publish failed";v(`Error: ${qt}`)}finally{setTimeout(()=>{d(null),v("")},3e3)}return wt&&!ut},[t,Be,A]),Mt=w.useCallback(ae=>{ae.startsWith("_new_")&&(q(we=>we.filter(ze=>ze!==ae)),St.current.delete(ae),fi.current.delete(ae),ne.current.delete(ae),_e.current.delete(ae),te(we=>{if(!(ae in we))return we;const ze={...we};return delete ze[ae],ze}),$(we=>{if(!(ae in we))return we;const ze={...we};return delete ze[ae],ze}))},[]);w.useEffect(()=>{const ae=ze=>{be(new Set(ze.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Ee(new Set(ze.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const Rt={},_t={},Je={},ut={},at={},wt={};for(const Xe of ze)Rt[Xe.name]=Xe.contentType||"fiction",_t[Xe.name]=Xe.language,Je[Xe.name]=Xe.genre,ut[Xe.name]=Xe.isNsfw,at[Xe.name]=Xe.agentProvider,Xe.title&&(wt[Xe.name]=Xe.title);je(Rt),Ce(_t),pt(Je),Ae(ut),ci(at),At(wt)};t("/api/stories").then(ze=>ze.ok?ze.json():null).then(ze=>{ze!=null&&ze.stories&&ae(ze.stories)}).catch(()=>{});const we=setInterval(async()=>{try{const ze=await t("/api/stories");if(ze.ok){const Rt=await ze.json();ae(Rt.stories)}}catch{}},5e3);return()=>clearInterval(we)},[t]);const Dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",pi=!!T&&!Dt,kt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),ki=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const ae=i;if((await t(`/api/stories/${ae}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ci(ze=>({...ze,[ae]:"codex"})),$(ze=>({...ze,[ae]:"codex"}));try{const ze=await t("/api/stories");if(ze.ok){const Rt=await ze.json();if(Rt!=null&&Rt.stories){const _t={};for(const Je of Rt.stories)_t[Je.name]=Je.agentProvider;ci(_t)}}}catch{}}},[t,i]),mi=w.useCallback(ae=>{i===ae&&(s(null),o(null))},[i]),Gt=i?oe[i]??Ot[i]:void 0,mn=Mf(i,Be,St.current),de=oD(mn,Gt,i),Re=!!i&&mn==="cartoon",We=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",st=w.useCallback(ae=>{const we=i;if(we)switch(ae){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":me(we,"structure.md");break;case"genesis":me(we,"genesis.md");break;case"publish":h("publish");break}},[i,me]),nt=w.useCallback((ae,we)=>{const ze=i;if(ze)switch(ae){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":we&&me(ze,we);break}},[i,me]),ct=w.useCallback(ae=>{i&&(ae.genre!==void 0&&pt(we=>({...we,[i]:ae.genre||void 0})),ae.language!==void 0&&Ce(we=>({...we,[i]:ae.language||void 0})),ae.isNsfw!==void 0&&Ae(we=>({...we,[i]:ae.isNsfw})))},[i]);return f.jsxs("div",{ref:Qe,className:"h-[calc(100vh-3.5rem)] flex",children:[f.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:f.jsx(bC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:me,onNewStory:ge,untitledSessions:J})}),f.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${D} 0 0`},children:f.jsx(WE,{token:e,storyName:i,authFetch:t,onSelectStory:Le,onDestroySession:Mt,onArchiveStory:mi,confirmedStories:ue,renameRef:Fe,bypassStories:se,agentProviders:oe,readiness:T,contentType:Mf(i,Be,St.current),needsProviderRepair:de,onRepairProvider:ki})}),f.jsx("div",{onMouseDown:ht,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Of,cursor:"col-resize",background:"var(--border)"},children:f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),f.jsxs("div",{className:"min-w-0 flex flex-col",style:{flex:`${1-D} 0 0`},children:[Re&&i&&f.jsx(MD,{storyTitle:Ve[i]||i,active:We,onSelect:st}),Re&&i&&c!==null&&f.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:f.jsx(_D,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:nt,onOpenStoryInfo:()=>h("story-info")})}),Re&&c==="story-info"&&i?f.jsx(DD,{storyName:i,authFetch:t,onSaved:ct}):Re&&c==="episodes"&&i?f.jsx(BD,{storyName:i,authFetch:t,onOpenFile:me}):Re&&c==="publish"&&i?f.jsx(LD,{storyName:i,authFetch:t,onOpenFile:me,onOpenStoryInfo:()=>h("story-info"),onPublish:it,publishingFile:p,genre:tt[i],language:Ze[i],isNsfw:Ge[i],refreshKey:_}):i&&!a?f.jsx(vD,{storyName:i,authFetch:t,onOpenFile:me,onOpenStoryInfo:()=>h("story-info")}):f.jsx(mD,{storyName:i,fileName:a,authFetch:t,onPublish:it,publishingFile:p,walletAddress:A,contentType:Mf(i,Be,St.current)||"fiction",language:i?Ze[i]:void 0,genre:i?tt[i]:void 0,isNsfw:i?Ge[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:ae=>i&&me(i,ae),onViewPublish:()=>h("publish")}),b&&f.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),y&&f.jsxs("div",{className:"px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[f.jsx("span",{children:y}),f.jsx("button",{type:"button",onClick:()=>N(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),L&&f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[f.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",f.jsx("span",{className:"text-accent",children:"*"})]}),f.jsx("input",{type:"text",value:he,onChange:ae=>ye(ae.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),f.jsx("input",{type:"text",value:U,onChange:ae=>re(ae.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),f.jsxs("select",{value:W,onChange:ae=>G(ae.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"— Select later —"}),nl.map(ae=>f.jsx("option",{value:ae,children:ae},ae))]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),f.jsx("select",{value:X,onChange:ae=>I(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:Xr.map(ae=>f.jsx("option",{value:ae,children:ae},ae))})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),f.jsxs("select",{value:j,onChange:ae=>O(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[f.jsx("option",{value:"normal",children:"Normal (approve each action)"}),f.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),j==="bypass"&&f.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),f.jsxs("select",{value:B,onChange:ae=>xe(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[f.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),f.jsx("option",{value:"codex",children:"🎨 Codex"})]}),f.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:B==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),f.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!he.trim()&&f.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),f.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[f.jsxs("button",{onClick:()=>Te("fiction",X,j,B),disabled:!he.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),f.jsxs("div",{className:"space-y-1",children:[f.jsxs("button",{onClick:()=>Te("cartoon",X,j,"codex"),disabled:pi||!he.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),f.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&f.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Su(T)&&f.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:zp}),T&&T.codex.installed&&!Su(T)&&T.codex.imageGeneration!=="enabled"&&f.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[f.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),f.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:kt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:Y?"Copied!":"Copy"})]})]})]})]}),f.jsx("button",{onClick:()=>Z(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function $D({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const d=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await d.json();if(!d.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(d){o(d instanceof Error?d.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),f.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[f.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),f.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&f.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),f.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"text-accent text-2xl",children:"✓"}),f.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),f.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function FD({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(d,_)=>fetch(d,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(d=>d.json()).then(d=>{d.version&&h(d.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function d(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(y=>y.name!=="_example").length)}}catch{}}d()},[e]),f.jsxs("div",{className:"flex h-screen flex-col",children:[f.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:f.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),f.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&f.jsxs("nav",{className:"flex items-center gap-4",children:[f.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),f.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),f.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),f.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),f.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),f.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&f.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),f.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[f.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),f.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[f.jsxs("li",{children:["Open the ",f.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),f.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),f.jsx("li",{children:"Review the live preview as the agent creates files"}),f.jsxs("li",{children:["Click ",f.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),f.jsxs("li",{children:["Earn 5% royalties on every trade at ",f.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),f.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),f.jsx("div",{className:"text-center",children:f.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),f.jsx(Sy,{token:e})]}),i==="stories"&&f.jsx(UD,{token:e,authFetch:p}),i==="dashboard"&&f.jsx(gC,{token:e}),i==="wallet-setup"&&f.jsx($D,{token:e,onComplete:()=>s("home")}),i==="settings"&&f.jsx(pC,{token:e,onLogout:t})]})]})}function qD(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(d=>d.json()).then(d=>s(d.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(d=>{d.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async d=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),null):x.error||"Login failed"}catch{return"Cannot connect to server"}},h=async d=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),s(!0),null):x.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?f.jsx("div",{className:"flex h-screen items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?f.jsx(FD,{token:e,onLogout:p}):f.jsx(dC,{onLogin:c}):f.jsx(fC,{onSetup:h})}hC.createRoot(document.getElementById("root")).render(f.jsx(nC.StrictMode,{children:f.jsx(qD,{})}));export{Dp as M,su as a,N3 as b,BM as c,j3 as d,ru as l,BS as s,U3 as t,VD as v}; diff --git a/app/web/dist/assets/index-DP8e99_8.css b/app/web/dist/assets/index-DP8e99_8.css new file mode 100644 index 0000000..b9de878 --- /dev/null +++ b/app/web/dist/assets/index-DP8e99_8.css @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@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-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--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}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--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);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.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:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.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}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:calc(var(--spacing) * 44)}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-52{width:calc(var(--spacing) * 52)}.w-56{width:calc(var(--spacing) * 56)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.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-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.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-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.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-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)}.ring{--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-2{--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)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.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-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))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@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-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@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} diff --git a/app/web/dist/assets/index-DaYKqthY.css b/app/web/dist/assets/index-DaYKqthY.css deleted file mode 100644 index 3b604da..0000000 --- a/app/web/dist/assets/index-DaYKqthY.css +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2014 The xterm.js authors. All rights reserved. - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * https://github.com/chjj/term.js - * @license MIT - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - * The original design remains. The terminal itself - * has been extended to include xterm CSI codes, among - * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@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-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--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}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--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);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.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:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.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}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:calc(var(--spacing) * 44)}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-52{width:calc(var(--spacing) * 52)}.w-56{width:calc(var(--spacing) * 56)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.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-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.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-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.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)}.ring{--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-2{--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)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.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-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))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@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-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@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} diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 2c114b0..2c67e3b 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,8 +7,8 @@ - - + +