From 6f6129a63e5a74b0073ade106987b30576ca87d3 Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:06:57 +0000 Subject: [PATCH 1/4] Move cartoon next action to persistent CTA --- app/web/components/CartoonNextAction.test.tsx | 115 +++++++++++ app/web/components/CartoonNextAction.tsx | 190 ++++++++++++++---- app/web/components/PreviewPanel.test.tsx | 23 +-- app/web/components/PreviewPanel.tsx | 59 ------ app/web/components/StoriesPage.test.tsx | 25 ++- app/web/components/StoriesPage.tsx | 33 ++- .../components/StoryProgressPanel.test.tsx | 42 +--- app/web/components/StoryProgressPanel.tsx | 29 +-- ...cut-HPHvubLr.js => export-cut-BuLQ0Lx7.js} | 2 +- app/web/dist/assets/index-B1vSuADc.css | 32 +++ .../{index-BGjpCebA.js => index-BLc-rD_a.js} | 96 ++++----- app/web/dist/assets/index-Bi-xodT8.css | 32 --- app/web/dist/index.html | 4 +- 13 files changed, 406 insertions(+), 276 deletions(-) create mode 100644 app/web/components/CartoonNextAction.test.tsx rename app/web/dist/assets/{export-cut-HPHvubLr.js => export-cut-BuLQ0Lx7.js} (98%) create mode 100644 app/web/dist/assets/index-B1vSuADc.css rename app/web/dist/assets/{index-BGjpCebA.js => index-BLc-rD_a.js} (61%) delete mode 100644 app/web/dist/assets/index-Bi-xodT8.css diff --git a/app/web/components/CartoonNextAction.test.tsx b/app/web/components/CartoonNextAction.test.tsx new file mode 100644 index 0000000..b7fc817 --- /dev/null +++ b/app/web/components/CartoonNextAction.test.tsx @@ -0,0 +1,115 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; +import { CartoonNextActionView } from "./CartoonNextAction"; + +beforeEach(() => { + Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); +}); + +describe("CartoonNextActionView", () => { + it("renders the compact Story Info CTA when cover metadata is the current gate", () => { + const onOpenStoryInfo = vi.fn(); + render( + , + ); + + const cta = screen.getByTestId("story-info-cta"); + expect(cta).toHaveTextContent("Next: Add a cover image before publishing."); + fireEvent.click(screen.getByRole("button", { name: "Next Action" })); + expect(onOpenStoryInfo).toHaveBeenCalledTimes(1); + }); + + it("renders the compact workflow CTA and routes UI actions without the old card shell", () => { + const onCoachAction = vi.fn(); + render( + , + ); + + expect(screen.getByTestId("cartoon-next-action")).toHaveTextContent( + "Next: Review cuts and start lettering", + ); + expect(screen.queryByTestId("workflow-coach")).not.toBeInTheDocument(); + fireEvent.click(screen.getByTestId("workflow-coach-do")); + expect(onCoachAction).toHaveBeenCalledWith("open-lettering", "genesis.md"); + }); +}); diff --git a/app/web/components/CartoonNextAction.tsx b/app/web/components/CartoonNextAction.tsx index 19ea48f..71a3744 100644 --- a/app/web/components/CartoonNextAction.tsx +++ b/app/web/components/CartoonNextAction.tsx @@ -1,7 +1,6 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import type { StoryProgress } from "@app-lib/story-progress"; -import type { CoachUiAction } from "@app-lib/cartoon-coach"; -import { WorkflowCoachView } from "./WorkflowCoach"; +import type { CartoonCoach, CoachUiAction } from "@app-lib/cartoon-coach"; export function storyInfoNextStep(progress: StoryProgress): string { if (progress.cover !== "present") { @@ -34,39 +33,161 @@ export function cartoonWorkflowActiveKey(progress: StoryProgress): string | null return coach?.episodeFile ?? null; } -export function StoryInfoNextActionCard({ - progress, - onOpenStoryInfo, +function CompactNextActionShell({ + badge, + tone = "accent", + summary, + children, + note, + testId, }: { - progress: StoryProgress; - onOpenStoryInfo?: () => void; + badge: string; + tone?: "accent" | "complete"; + summary: ReactNode; + children?: ReactNode; + note?: ReactNode; + testId: string; }) { + const shellTone = + tone === "complete" + ? "border-green-700/20 bg-green-950/5" + : "border-accent/30 bg-background/95"; + const badgeTone = + tone === "complete" + ? "bg-green-700/10 text-green-700" + : "bg-accent/10 text-accent"; return ( -
-
+
+
- - Story info + + {badge} -

- Next: - {storyInfoNextStep(progress)} -

+

{summary}

+ {note ?

{note}

: null}
- + {children ? ( +
+ {children} +
+ ) : null}
); } +function NextActionButton({ + onClick, + disabled, + testId, +}: { + onClick: () => void; + disabled?: boolean; + testId: string; +}) { + return ( + + ); +} + +function WorkflowCoachCompact({ + coach, + onAction, +}: { + coach: CartoonCoach | null | undefined; + onAction: (action: CoachUiAction, episodeFile: string | null) => void; +}) { + const [copiedPrompt, setCopiedPrompt] = useState(null); + const copied = copiedPrompt !== null && copiedPrompt === coach?.prompt; + + if (coach === undefined) return null; + if (!coach) { + return ( + + ); + } + + const button = + coach.actionKind === "agent" && coach.prompt ? ( + { + if (!coach.prompt) return; + const prompt = coach.prompt; + navigator.clipboard?.writeText(prompt).then(() => setCopiedPrompt(prompt)).catch(() => {}); + }} + /> + ) : coach.actionKind === "ui" && coach.uiAction ? ( + onAction(coach.uiAction!, coach.episodeFile)} + /> + ) : null; + + return ( + + Next: + {coach.action} + + )} + note={copied ? "Prompt copied." : undefined} + testId="cartoon-next-action" + > + {button} + + ); +} + +export function StoryInfoNextActionCard({ + progress, + onOpenStoryInfo, +}: { + progress: StoryProgress; + onOpenStoryInfo?: () => void; +}) { + return ( + + Next: + {storyInfoNextStep(progress)} + + )} + testId="story-info-cta" + > + onOpenStoryInfo?.()} + disabled={!onOpenStoryInfo} + /> + + ); +} + export function CartoonNextActionView({ progress, onCoachAction, @@ -80,31 +201,27 @@ export function CartoonNextActionView({ if (activeKey === "story-info") { return ; } - return ( - - ); + return ; } export function CartoonNextAction({ storyName, authFetch, + fileName, refreshKey = 0, onCoachAction, onOpenStoryInfo, }: { storyName: string; authFetch: (url: string, opts?: RequestInit) => Promise; + fileName?: string | null; refreshKey?: number; onCoachAction: (action: CoachUiAction, episodeFile: string | null) => void; onOpenStoryInfo?: () => void; }) { const [progress, setProgress] = useState(undefined); - const targetKey = JSON.stringify([storyName, refreshKey]); + const targetKey = JSON.stringify([storyName, fileName ?? "", refreshKey]); const [loadedKey, setLoadedKey] = useState(null); if (loadedKey !== targetKey) { setProgress(undefined); @@ -113,7 +230,8 @@ export function CartoonNextAction({ useEffect(() => { let cancelled = false; - authFetch(`/api/stories/${storyName}/progress`) + const focus = fileName ? `?focus=${encodeURIComponent(fileName)}` : ""; + authFetch(`/api/stories/${storyName}/progress${focus}`) .then((res) => (res.ok ? res.json() : null)) .then((data: StoryProgress | null) => { if (!cancelled) setProgress(isValidProgress(data) ? data : null); @@ -122,11 +240,11 @@ export function CartoonNextAction({ if (!cancelled) setProgress(null); }); return () => { cancelled = true; }; - }, [storyName, authFetch, refreshKey]); + }, [storyName, fileName, authFetch, refreshKey]); if (progress === undefined) return null; if (!progress) { - return ; + return ; } return ( { - it("a Genesis coach UI action lands on the actionable cut workspace, not the markdown editor", async () => { +describe("PreviewPanel — cartoon file chrome", () => { + it("does not render the old top workflow coach in cartoon file views (#498)", async () => { render(); - - // The coach loads for Genesis with an in-app (lettering) action. - const doBtn = await screen.findByTestId("workflow-coach-do"); - 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(); - - fireEvent.click(doBtn); - - // After: the Genesis cut workspace is mounted and actionable — NOT the - // plain markdown textarea (the bug @re1 caught). - expect(await screen.findByTestId("cut-list-panel")).toBeInTheDocument(); + expect(await screen.findByText("The story begins.")).toBeInTheDocument(); + expect(screen.queryByTestId("workflow-coach")).not.toBeInTheDocument(); }); it("Genesis Edit tab keeps the opening-text editor and reaches the cut workspace via the sub-toggle", async () => { render(); - await screen.findByTestId("workflow-coach"); // wait for first render to settle + await screen.findByText("The story begins."); fireEvent.click(screen.getByRole("button", { name: /^Edit/ })); // Default Genesis Edit sub-view is the opening-text editor (prose preserved). @@ -94,7 +83,7 @@ describe("PreviewPanel — Genesis workflow-coach cut actions (#429)", () => { />, ); - await screen.findByTestId("workflow-coach"); + await screen.findByText("The story begins."); for (let i = 0; i < 2; i++) { fireEvent.click(screen.getByRole("button", { name: /^Edit/ })); diff --git a/app/web/components/PreviewPanel.tsx b/app/web/components/PreviewPanel.tsx index 793d2c7..4ae033b 100644 --- a/app/web/components/PreviewPanel.tsx +++ b/app/web/components/PreviewPanel.tsx @@ -7,8 +7,6 @@ import { GENRES, LANGUAGES, canonicalizeGenre } from "../../../lib/genres"; import { CartoonPreview } from "./CartoonPreview"; import { CartoonPublishPreview } from "./CartoonPublishPreview"; import { CutListPanel } from "./CutListPanel"; -import { WorkflowCoach } from "./WorkflowCoach"; -import type { CoachUiAction } from "@app-lib/cartoon-coach"; import { classifyCartoonReadiness, cartoonGenesisReadiness, @@ -533,44 +531,6 @@ export function PreviewPanel({ } }, [storyName, fileName, authFetch, loadFile]); - // Route a workflow-coach UI action to the right control (#429). When the - // action concerns a different episode than the open file (e.g. the coach on - // structure.md points at the active episode), open that file first — the coach - // there offers the same action in place. Otherwise reveal the control: the cut - // workspace for letter/export/upload/refresh, the Preview tab for publish (the - // writer still confirms the irreversible publish), or run Prepare directly. - const handleCoachAction = useCallback( - (action: CoachUiAction, episodeFile: string | null) => { - if (action === "view-progress") { - onViewProgress?.(); - return; - } - if (episodeFile && episodeFile !== fileName) { - onOpenFile?.(episodeFile); - return; - } - switch (action) { - case "open-cuts": - case "open-lettering": - case "upload": - case "refresh-assets": - setActiveTab("edit"); - // For Genesis the Edit tab defaults to the opening-text editor; switch to - // the cut workspace so the lettering/upload/refresh action is actionable. - // No-op for plots (the cut workspace is the only Edit view). - setGenesisEditMode("cuts"); - break; - case "generate-markdown": - handleGenerateMarkdown(); - break; - case "publish": - setActiveTab("preview"); - break; - } - }, - [fileName, onViewProgress, onOpenFile, handleGenerateMarkdown], - ); - // Handle cover image selection const handleCoverSelect = useCallback( (e: React.ChangeEvent) => { @@ -1331,25 +1291,6 @@ export function PreviewPanel({
)} - {/* Persistent cartoon workflow coach (#429): one clear next action across - every cartoon file view, derived from real story/episode state. Sits - above the content so it stays visible on both the Preview and Edit - tabs. Fiction renders nothing (the coach is null), so fiction views are - unchanged. */} - {!hideFocusedEditorChrome && - contentType === "cartoon" && - storyName && - fileName && ( - - )} - {/* Content area */} {activeTab === "preview" ? ( isCartoonPlot ? ( diff --git a/app/web/components/StoriesPage.test.tsx b/app/web/components/StoriesPage.test.tsx index fe5b23e..e5ec852 100644 --- a/app/web/components/StoriesPage.test.tsx +++ b/app/web/components/StoriesPage.test.tsx @@ -780,7 +780,7 @@ function makeTwoCartoonAuthFetch() { ok: true, json: () => Promise.resolve({ stories }), }); - if (url.endsWith("/progress")) + if (url.includes("/progress")) return Promise.resolve({ ok: true, json: () => Promise.resolve(progress), @@ -847,15 +847,16 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { 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 () => { + it("shows the persistent Story Info next-action CTA at the bottom of cartoon 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")); + expect(screen.queryByTestId("workflow-context-next-action")).not.toBeInTheDocument(); const publishCta = await screen.findByTestId( - "workflow-context-next-action", + "workflow-persistent-next-action", ); expect( within(publishCta).getByTestId("story-info-next-action"), @@ -877,7 +878,7 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { ), ); - const storyInfoCta = screen.getByTestId("workflow-context-next-action"); + const storyInfoCta = screen.getByTestId("workflow-persistent-next-action"); expect( within(storyInfoCta).getByTestId("story-info-next-action"), ).toHaveTextContent(/Next: Add a cover image before publishing/i); @@ -885,4 +886,20 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { within(storyInfoCta).queryByText("No next action available"), ).not.toBeInTheDocument(); }, 10000); + + it("keeps the persistent CTA on file-backed cartoon routes without restoring the old top strip", async () => { + const { fn } = makeTwoCartoonAuthFetch(); + render(); + await waitFor(() => expect(childProps.onSelectFile).not.toBeNull()); + + childProps.onSelectFile!("cartoon-a", "genesis.md"); + await waitFor(() => expect(childProps.previewFile).toBe("genesis.md")); + + expect(screen.queryByTestId("workflow-context-next-action")).not.toBeInTheDocument(); + const cta = await screen.findByTestId("workflow-persistent-next-action"); + expect(within(cta).getByTestId("story-info-next-action")).toHaveTextContent( + /Next: Add a cover image before publishing/i, + ); + expect(within(cta).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); + }, 10000); }); diff --git a/app/web/components/StoriesPage.tsx b/app/web/components/StoriesPage.tsx index 6986c44..412306f 100644 --- a/app/web/components/StoriesPage.tsx +++ b/app/web/components/StoriesPage.tsx @@ -1211,23 +1211,6 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { onSelect={handleCartoonNav} /> )} - {!focusedLetteringMode && - isCartoonStory && - selectedStory && - cartoonView !== null && ( -
- setCartoonView("story-info")} - /> -
- )}
{isCartoonStory && cartoonView === "story-info" && selectedStory ? ( setCartoonView("story-info")} /> ) : ( )}
+ {!focusedLetteringMode && isCartoonStory && selectedStory && ( +
+ setCartoonView("story-info")} + /> +
+ )} {publishProgress && (
{publishProgress} diff --git a/app/web/components/StoryProgressPanel.test.tsx b/app/web/components/StoryProgressPanel.test.tsx index 25101d1..5cace1d 100644 --- a/app/web/components/StoryProgressPanel.test.tsx +++ b/app/web/components/StoryProgressPanel.test.tsx @@ -119,30 +119,14 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { expect(screen.getByTestId("workflow-section-4")).toHaveTextContent("Episode 2"); }); - it("places exactly one prominent persistent next-action CTA above the workflow map", async () => { + it("leaves next-action rendering to the surrounding right-pane shell", async () => { render(); await screen.findByTestId("story-progress-panel"); - const nextAction = screen.getByTestId("persistent-next-action"); - expect(within(nextAction).getAllByTestId("workflow-coach")).toHaveLength(1); + expect(screen.queryByTestId("persistent-next-action")).toBeNull(); expect(screen.queryByTestId("section-cta")).toBeNull(); - - // 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(genesisSection).toHaveAttribute("data-status", "current"); - - 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 () => { - const onOpenFile = vi.fn(); - render(); - await screen.findByTestId("story-progress-panel"); - fireEvent.click(screen.getByTestId("workflow-coach-do")); - expect(onOpenFile).toHaveBeenCalledWith("god-cell", "genesis.md"); }); it("shows per-step checklist items in the Genesis section", async () => { @@ -173,18 +157,11 @@ 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 () => { - const onOpenStoryInfo = vi.fn(); - render(); + render(); await screen.findByTestId("story-progress-panel"); 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); + expect(screen.queryByTestId("persistent-next-action")).toBeNull(); const info = screen.getByTestId("workflow-section-1"); expect(info).toHaveAttribute("data-status", "current"); @@ -201,10 +178,8 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { render(); await screen.findByTestId("story-progress-panel"); - 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(); + expect(screen.queryByTestId("persistent-next-action")).toBeNull(); // Genesis (Episode 1) remains the current workflow section. const genesis = screen.getByTestId("workflow-section-3"); @@ -215,9 +190,6 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { const info = screen.getByTestId("workflow-section-1"); expect(info).not.toHaveAttribute("data-status", "current"); expect(within(info).getByText(/Missing/)).toBeInTheDocument(); - // The cover CTA / "add a cover" wording must not appear anywhere. - expect(screen.queryByTestId("story-info-cta")).toBeNull(); - expect(screen.queryByText(/Add a cover image/i)).toBeNull(); }); // #444 RE2: with the bible written but Genesis not yet written, the @@ -226,10 +198,8 @@ describe("StoryProgressPanel — cartoon workflow map (#438)", () => { render(); await screen.findByTestId("story-progress-panel"); - 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(); + expect(screen.queryByTestId("persistent-next-action")).toBeNull(); // Whitepaper is complete; the Genesis (Episode 1) section is the current step. expect(screen.getByTestId("workflow-section-2")).toHaveAttribute("data-status", "done"); diff --git a/app/web/components/StoryProgressPanel.tsx b/app/web/components/StoryProgressPanel.tsx index 33ca610..d4c6e21 100644 --- a/app/web/components/StoryProgressPanel.tsx +++ b/app/web/components/StoryProgressPanel.tsx @@ -1,15 +1,13 @@ import { useEffect, useState } from "react"; import type { StoryProgress, EpisodeProgress, EpisodeState } from "@app-lib/story-progress"; import type { CartoonChecklistStep } from "@app-lib/cartoon-readiness"; -import { cartoonWorkflowActiveKey, CartoonNextActionView } from "./CartoonNextAction"; +import { cartoonWorkflowActiveKey } 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; } @@ -20,13 +18,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 stays persistent above the map, while the - * current section still marks where that action belongs. + * status. The shell owns the single persistent next-action CTA, 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, onOpenStoryInfo, refreshKey = 0 }: StoryProgressPanelProps) { +export function StoryProgressPanel({ storyName, authFetch, onOpenFile, refreshKey = 0 }: StoryProgressPanelProps) { const [progress, setProgress] = useState(null); const [loading, setLoading] = useState(true); @@ -56,7 +54,7 @@ export function StoryProgressPanel({ storyName, authFetch, onOpenFile, onOpenSto } return progress.contentType === "cartoon" - ? + ? : ; } @@ -203,12 +201,11 @@ const GENESIS_STUB: EpisodeProgress = { }; function CartoonWorkflowMap({ - progress, storyName, onOpenFile, onOpenStoryInfo, + progress, storyName, onOpenFile, }: { progress: StoryProgress; storyName: string; onOpenFile: (storyName: string, file: string) => void; - onOpenStoryInfo?: () => void; }) { const m = progress.metadata; const hasStructure = progress.setup.hasStructure; @@ -217,17 +214,6 @@ function CartoonWorkflowMap({ const storyInfoIncomplete = metadataIncomplete || !coverDone; const activeKey = cartoonWorkflowActiveKey(progress); - const topNextAction = ( - { - if (action === "view-progress") return; // already here - if (episodeFile) onOpenFile(storyName, episodeFile); - }} - /> - ); - 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 }, @@ -245,9 +231,6 @@ function CartoonWorkflowMap({ return (
-
- {topNextAction} -

Production Progress

"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-BLc-rD_a.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-B1vSuADc.css b/app/web/dist/assets/index-B1vSuADc.css new file mode 100644 index 0000000..278fdde --- /dev/null +++ b/app/web/dist/assets/index-B1vSuADc.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;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia: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-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-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.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-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.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}.justify-end{justify-content:flex-end}.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\/20{border-color:#00813833}@supports (color:color-mix(in lab,red,red)){.border-green-700\/20{border-color:color-mix(in oklab,var(--color-green-700) 20%,transparent)}}.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-\[\#f8f5ef\]{background-color:#f8f5ef}.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-background\/95{background-color:#e8dfd0f2}.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\/35{background-color:#f0ebe159}.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-surface\/95{background-color:#f0ebe1f2}.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,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.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\:w-auto{width:auto}.sm\:flex-shrink-0{flex-shrink:0}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:px-4{padding-inline:calc(var(--spacing) * 4)}}}: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}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false} diff --git a/app/web/dist/assets/index-BGjpCebA.js b/app/web/dist/assets/index-BLc-rD_a.js similarity index 61% rename from app/web/dist/assets/index-BGjpCebA.js rename to app/web/dist/assets/index-BLc-rD_a.js index 164a116..3c89a1d 100644 --- a/app/web/dist/assets/index-BGjpCebA.js +++ b/app/web/dist/assets/index-BLc-rD_a.js @@ -1,4 +1,4 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Pu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Kd={exports:{}},lo={};/** +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Lu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yd={exports:{}},so={};/** * @license React * react-jsx-runtime.production.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 tb;function fC(){if(tb)return lo;tb=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 lo.Fragment=t,lo.jsx=i,lo.jsxs=i,lo}var ib;function pC(){return ib||(ib=1,Kd.exports=fC()),Kd.exports}var d=pC(),Vd={exports:{}},it={};/** + */var ib;function pC(){if(ib)return so;ib=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 so.Fragment=t,so.jsx=i,so.jsxs=i,so}var nb;function mC(){return nb||(nb=1,Yd.exports=pC()),Yd.exports}var d=mC(),Vd={exports:{}},it={};/** * @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 nb;function mC(){if(nb)return it;nb=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"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(M){return M===null||typeof M!="object"?null:(M=b&&M[b]||M["@@iterator"],typeof M=="function"?M:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,D={};function E(M,V,C){this.props=M,this.context=V,this.refs=D,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(M,V){if(typeof M!="object"&&typeof M!="function"&&M!=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,M,V,"setState")},E.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function N(){}N.prototype=E.prototype;function I(M,V,C){this.props=M,this.context=V,this.refs=D,this.updater=C||S}var te=I.prototype=new N;te.constructor=I,j(te,E.prototype),te.isPureReactComponent=!0;var q=Array.isArray;function R(){}var ie={H:null,A:null,T:null,S:null},fe=Object.prototype.hasOwnProperty;function be(M,V,C){var X=C.ref;return{$$typeof:e,type:M,key:V,ref:X!==void 0?X:null,props:C}}function B(M,V){return be(M.type,V,M.props)}function ne(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function F(M){var V={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(C){return V[C]})}var G=/\/+/g;function Y(M,V){return typeof M=="object"&&M!==null&&M.key!=null?F(""+M.key):V.toString(36)}function U(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(R,R):(M.status="pending",M.then(function(V){M.status==="pending"&&(M.status="fulfilled",M.value=V)},function(V){M.status==="pending"&&(M.status="rejected",M.reason=V)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function A(M,V,C,X,se){var le=typeof M;(le==="undefined"||le==="boolean")&&(M=null);var K=!1;if(M===null)K=!0;else switch(le){case"bigint":case"string":case"number":K=!0;break;case"object":switch(M.$$typeof){case e:case t:K=!0;break;case _:return K=M._init,A(K(M._payload),V,C,X,se)}}if(K)return se=se(M),K=X===""?"."+Y(M,0):X,q(se)?(C="",K!=null&&(C=K.replace(G,"$&/")+"/"),A(se,V,C,"",function(Me){return Me})):se!=null&&(ne(se)&&(se=B(se,C+(se.key==null||M&&M.key===se.key?"":(""+se.key).replace(G,"$&/")+"/")+K)),V.push(se)),1;K=0;var he=X===""?".":X+":";if(q(M))for(var _e=0;_e>>1,T=A[ge];if(0>>1;gea(C,$))Xa(se,C)?(A[ge]=se,A[X]=$,ge=X):(A[ge]=C,A[V]=$,ge=V);else if(Xa(se,$))A[ge]=se,A[X]=$,ge=X;else break e}}return z}function a(A,z){var $=A.sortIndex-z.sortIndex;return $!==0?$:A.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,j=!1,D=!1,E=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=A)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(A){if(j=!1,te(A),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(q,z.startTime-A)}}var R=!1,ie=-1,fe=5,be=-1;function B(){return D?!0:!(e.unstable_now()-beA&&B());){var ge=x.callback;if(typeof ge=="function"){x.callback=null,b=x.priorityLevel;var T=ge(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),z=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)z=!0;else{var M=i(f);M!==null&&U(q,M.startTime-A),z=!1}}break e}finally{x=null,b=$,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof I=="function")F=function(){I(ne)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,Y=G.port2;G.port1.onmessage=ne,F=function(){Y.postMessage(null)}}else F=function(){E(ne,0)};function U(A,z){ie=E(function(){A(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(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125ge?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(j?(N(ie),ie=-1):j=!0,U(q,$-ge))):(A.sortIndex=T,t(p,A),S||v||(S=!0,R||(R=!0,F()))),A},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(A){var z=b;return function(){var $=b;b=z;try{return A.apply(this,arguments)}finally{b=$}}}})(Qd)),Qd}var ab;function _C(){return ab||(ab=1,Zd.exports=xC()),Zd.exports}var Jd={exports:{}},tn={};/** + */var ab;function _C(){return ab||(ab=1,(function(e){function t(A,z){var $=A.length;A.push(z);e:for(;0<$;){var ge=$-1>>>1,T=A[ge];if(0>>1;gea(C,$))Xa(re,C)?(A[ge]=re,A[X]=$,ge=X):(A[ge]=C,A[K]=$,ge=K);else if(Xa(re,$))A[ge]=re,A[X]=$,ge=X;else break e}}return z}function a(A,z){var $=A.sortIndex-z.sortIndex;return $!==0?$:A.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=A)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(A){if(N=!1,te(A),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(q,z.startTime-A)}}var R=!1,ie=-1,fe=5,be=-1;function B(){return M?!0:!(e.unstable_now()-beA&&B());){var ge=x.callback;if(typeof ge=="function"){x.callback=null,b=x.priorityLevel;var T=ge(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),z=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&U(q,D.startTime-A),z=!1}}break e}finally{x=null,b=$,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof I=="function")F=function(){I(ne)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,Y=G.port2;G.port1.onmessage=ne,F=function(){Y.postMessage(null)}}else F=function(){E(ne,0)};function U(A,z){ie=E(function(){A(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(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125ge?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(N?(j(ie),ie=-1):N=!0,U(q,$-ge))):(A.sortIndex=T,t(p,A),S||v||(S=!0,R||(R=!0,F()))),A},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(A){var z=b;return function(){var $=b;b=z;try{return A.apply(this,arguments)}finally{b=$}}}})(Zd)),Zd}var lb;function bC(){return lb||(lb=1,Xd.exports=_C()),Xd.exports}var Qd={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 lb;function bC(){if(lb)return tn;lb=1;var e=Hp();function t(p){var f="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(),Jd.exports=bC(),Jd.exports}/** + */var ob;function vC(){if(ob)return Ji;ob=1;var e=Up();function t(p){var f="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(),Qd.exports=vC(),Qd.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 cb;function yC(){if(cb)return oo;cb=1;var e=_C(),t=Hp(),i=vC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=ge[T],ge[T]=null,T--)}function C(n,r){T++,ge[T]=n.current,n.current=r}var X=M(null),se=M(null),le=M(null),K=M(null);function he(n,r){switch(C(le,r),C(se,n),C(X,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?C_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=C_(r),n=k_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}V(X),C(X,n)}function _e(){V(X),V(se),V(le)}function Me(n){n.memoizedState!==null&&C(K,n);var r=X.current,l=k_(r,n.type);r!==l&&(C(se,n),C(X,l))}function Le(n){se.current===n&&(V(X),V(se)),K.current===n&&(V(K),no._currentValue=$)}var He,ke;function Ue(n){if(He===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);He=r&&r[1]||"",ke=-1T||(n.current=ge[T],ge[T]=null,T--)}function C(n,r){T++,ge[T]=n.current,n.current=r}var X=D(null),re=D(null),le=D(null),V=D(null);function he(n,r){switch(C(le,r),C(re,n),C(X,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}K(X),C(X,n)}function _e(){K(X),K(re),K(le)}function Me(n){n.memoizedState!==null&&C(V,n);var r=X.current,l=E_(r,n.type);r!==l&&(C(re,n),C(X,l))}function Le(n){re.current===n&&(K(X),K(re)),V.current===n&&(K(V),to._currentValue=$)}var He,Ce;function Ue(n){if(He===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);He=r&&r[1]||"",Ce=-1)":-1m||L[u]!==J[m]){var ue=` -`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{Je=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ue(l):""}function Ve(n,r){switch(n.tag){case 26:case 27:case 5:return Ue(n.type);case 16:return Ue("Lazy");case 13:return n.child!==r&&r!==null?Ue("Suspense Fallback"):Ue("Suspense");case 19:return Ue("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return Ue("Activity");default:return""}}function Et(n){try{var r="",l=null;do r+=Ve(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{et=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ue(l):""}function Ke(n,r){switch(n.tag){case 26:case 27:case 5:return Ue(n.type);case 16:return Ue("Lazy");case 13:return n.child!==r&&r!==null?Ue("Suspense Fallback"):Ue("Suspense");case 19:return Ue("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return Ue("Activity");default:return""}}function Et(n){try{var r="",l=null;do r+=Ke(n,l),l=n,n=n.return;while(n);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var ze=Object.prototype.hasOwnProperty,_t=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Kt=e.unstable_shouldYield,mi=e.unstable_requestPaint,wt=e.unstable_now,et=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,je=e.unstable_NormalPriority,$e=e.unstable_LowPriority,nt=e.unstable_IdlePriority,Wt=e.log,ui=e.unstable_setDisableYieldValue,Bt=null,yt=null;function Rt(n){if(typeof Wt=="function"&&ui(n),yt&&typeof yt.setStrictMode=="function")try{yt.setStrictMode(Bt,n)}catch{}}var Qe=Math.clz32?Math.clz32:Se,hi=Math.log,H=Math.LN2;function Se(n){return n>>>=0,n===0?32:31-(hi(n)/H|0)|0}var Oe=256,Ae=262144,Ge=4194304;function Fe(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Fe(u):(y&=k,y!==0?m=Fe(y):l||(l=k&~n,l!==0&&(m=Fe(l))))):(k=u&~g,k!==0?m=Fe(k):y!==0?m=Fe(y):l||(l=u&~n,l!==0&&(m=Fe(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 ft(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function ct(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 Vt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ci(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function pt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Fi(n,r,l,u,m,g){var y=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,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ei=/[\n"\\]/g;function gi(n){return n.replace(Ei,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Gi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ct(r)):n.value!==""+Ct(r)&&(n.value=""+Ct(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Or(n,y,Ct(r)):l!=null?Or(n,y,Ct(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=""+Ct(k):n.removeAttribute("name")}function jn(n,r,l,u,m,g,y,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?""+Ct(l):"",r=r!=null?""+Ct(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Lr(n)}function Or(n,r,l){r==="number"&&xr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Tn(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"),re=!1;if(Wn)try{var ye={};Object.defineProperty(ye,"passive",{get:function(){re=!0}}),window.addEventListener("test",ye,ye),window.removeEventListener("test",ye,ye)}catch{re=!1}var Ce=null,tt=null,Pt=null;function Ni(){if(Pt)return Pt;var n,r=tt,l=r.length,u,m="value"in Ce?Ce.value:Ce.textContent,g=m.length;for(n=0;n=Cl),Rm=" ",Dm=!1;function Mm(n,r){switch(n){case"keyup":return L1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Na=!1;function z1(n,r){switch(n){case"compositionend":return Bm(r);case"keypress":return r.which!==32?null:(Dm=!0,Rm);case"textInput":return n=r.data,n===Rm&&Dm?null:n;default:return null}}function P1(n,r){if(Na)return n==="compositionend"||!eh&&Mm(n,r)?(n=Ni(),Pt=tt=Ce=null,Na=!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=$m(l)}}function qm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?qm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Wm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xr(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=xr(n.document)}return r}function nh(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 G1=Wn&&"documentMode"in document&&11>=document.documentMode,ja=null,rh=null,jl=null,sh=!1;function Gm(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||ja==null||ja!==xr(u)||(u=ja,"selectionStart"in u&&nh(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}),jl&&Nl(jl,u)||(jl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-Qe(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var At=ee(W,Ie,Z[lt],de);if(At===null){Ie===null&&(Ie=vt);break}n&&Ie&&At.alternate===null&&r(W,Ie),P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At,Ie=vt}if(lt===Z.length)return l(W,Ie),St&&Pr(W,lt),qe;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Ds=ee(W,Ie,At.value,de);if(Ds===null){Ie===null&&(Ie=vt);break}n&&Ie&&Ds.alternate===null&&r(W,Ie),P=g(Ds,P,lt),Tt===null?qe=Ds:Tt.sibling=Ds,Tt=Ds,Ie=vt}if(At.done)return l(W,Ie),St&&Pr(W,lt),qe;if(Ie===null){for(;!At.done;lt++,At=Z.next())At=pe(W,At.value,de),At!==null&&(P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At);return St&&Pr(W,lt),qe}for(Ie=u(Ie);!At.done;lt++,At=Z.next())At=ae(Ie,W,lt,At.value,de),At!==null&&(n&&At.alternate!==null&&Ie.delete(At.key===null?lt:At.key),P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At);return n&&Ie.forEach(function(dC){return r(W,dC)}),St&&Pr(W,lt),qe}function Ut(W,P,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===j&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var qe=Z.key;P!==null;){if(P.key===qe){if(qe=Z.type,qe===j){if(P.tag===7){l(W,P.sibling),de=m(P,Z.props.children),de.return=W,W=de;break e}}else if(P.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===fe&&ta(qe)===P.type){l(W,P.sibling),de=m(P,Z.props),Bl(de,Z),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Z.type===j?(de=Xs(Z.props.children,W.mode,de,Z.key),de.return=W,W=de):(de=rc(Z.type,Z.key,Z.props,null,W.mode,de),Bl(de,Z),de.return=W,W=de)}return y(W);case S:e:{for(qe=Z.key;P!==null;){if(P.key===qe)if(P.tag===4&&P.stateNode.containerInfo===Z.containerInfo&&P.stateNode.implementation===Z.implementation){l(W,P.sibling),de=m(P,Z.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Z,W.mode,de),de.return=W,W=de}return y(W);case fe:return Z=ta(Z),Ut(W,P,Z,de)}if(U(Z))return Be(W,P,Z,de);if(F(Z)){if(qe=F(Z),typeof qe!="function")throw Error(s(150));return Z=qe.call(Z),Ke(W,P,Z,de)}if(typeof Z.then=="function")return Ut(W,P,hc(Z),de);if(Z.$$typeof===I)return Ut(W,P,lc(W,Z),de);dc(W,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Z),de.return=W,W=de):(l(W,P),de=hh(Z,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Z,de){try{Ml=0;var qe=Ut(W,P,Z,de);return Ia=null,qe}catch(Ie){if(Ie===Pa||Ie===cc)throw Ie;var Tt=Rn(29,Ie,null,W.mode);return Tt.lanes=de,Tt.return=W,Tt}finally{}}}var na=mg(!0),gg=mg(!1),ms=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 gs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function xs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Mt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),Jm(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ll(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,ln(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function Ol(){if(Nh){var n=za;if(n!==null)throw n}}function zl(n,r,l,u){Nh=!1;var m=n.updateQueue;ms=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=J=L=null,k=g;do{var ee=k.lane&-536870913,ae=ee!==k.lane;if(ae?(bt&ee)===ee:(u&ee)===ee){ee!==0&&ee===Oa&&(Nh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Be=n,Ke=k;ee=r;var Ut=l;switch(Ke.tag){case 1:if(Be=Ke.payload,typeof Be=="function"){pe=Be.call(Ut,pe,ee);break e}pe=Be;break e;case 3:Be.flags=Be.flags&-65537|128;case 0:if(Be=Ke.payload,ee=typeof Be=="function"?Be.call(Ut,pe,ee):Be,ee==null)break e;pe=x({},pe,ee);break e;case 2:ms=!0}}ee=k.callback,ee!==null&&(n.flags|=64,ae&&(n.flags|=8192),ae=m.callbacks,ae===null?m.callbacks=[ee]:ae.push(ee))}else ae={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=ae,L=pe):ue=ue.next=ae,y|=ee;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ae=k,k=ae.next,ae.next=null,m.lastBaseUpdate=ae,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Ss|=y,n.lanes=y,n.memoizedState=pe}}function xg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function _g(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Gh(n,!1,r,l);try{var L=m(),J=A.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=tw(L,u);Hl(n,r,ue,On(n))}else Hl(n,r,u,On(n))}catch(pe){Hl(n,r,{then:function(){},status:"rejected",reason:pe},On())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function lw(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Xg(n).queue;Vg(n,m,r,$,l===null?lw:function(){return Zg(n),l(u)})}function Xg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Zg(n){var r=Xg(n);r.next===null&&(r=n.alternate.memoizedState),Hl(n,r.next.queue,{},On())}function Wh(){return Vi(no)}function Qg(){return fi().memoizedState}function Jg(){return fi().memoizedState}function ow(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=On();n=gs(l);var u=xs(r,n,l);u!==null&&(Sn(u,r,l),Ll(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function cw(n,r,l){var u=On();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?tx(r,l):(l=ch(n,r,l,u),l!==null&&(Sn(l,n,u),ix(l,r,u)))}function ex(n,r,l){var u=On();Hl(n,r,l,u)}function Hl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))tx(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,An(k,y))return ic(n,r,m,0),Ft===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return Sn(l,n,u),ix(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&Sn(r,n,2)}function Sc(n){var r=n.alternate;return n===st||r!==null&&r===st}function tx(n,r){Ua=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function ix(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}var Ul={readContext:Vi,use:_c,useCallback:si,useContext:si,useEffect:si,useImperativeHandle:si,useLayoutEffect:si,useInsertionEffect:si,useMemo:si,useReducer:si,useRef:si,useState:si,useDebugValue:si,useDeferredValue:si,useTransition:si,useSyncExternalStore:si,useId:si,useHostTransitionStatus:si,useFormState:si,useActionState:si,useOptimistic:si,useMemoCache:si,useCacheRefresh:si};Ul.useEffectEvent=si;var nx={readContext:Vi,use:_c,useCallback:function(n,r){return un().memoizedState=[n,r===void 0?null:r],n},useContext:Vi,useEffect:Hg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,qg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=un();r=r===void 0?null:r;var u=n();if(ra){Rt(!0);try{n()}finally{Rt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=un();if(l!==void 0){var m=l(r);if(ra){Rt(!0);try{l(r)}finally{Rt(!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=cw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=un();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=ex.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=un();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Vg.bind(null,st,n.queue,!0,!1),un().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=un();if(St){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(bt&127)!==0||Cg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Hg(Eg.bind(null,u,g,n),[n]),u.flags|=2048,Fa(9,{destroy:void 0},kg.bind(null,u,g,l,r),null),l},useId:function(){var n=un(),r=Ft.identifierPrefix;if(St){var l=Sr,u=yr;l=(u&~(1<<32-Qe(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[oe]=r,g[O]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Zi(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&&qr(r)}}return Zt(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=le.current,Ba(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Ki,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[oe]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||S_(n.nodeValue,l)),n||fs(r,!0)}else n=$c(n).createTextNode(u),n[oe]=r,r.stateNode=n}return Zt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ba(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[oe]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Mn(r),r):(Mn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Zt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ba(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[oe]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Mn(r),r):(Mn(r),null)}return Mn(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),Nc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&jd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(V(di),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Fl(u,!1);else{if(ai!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,Fl(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)eg(l,n),l=l.sibling;return C(di,di.current&1|2),St&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&wt()>Dc&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),Fl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!St)return Zt(r),null}else 2*wt()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,Fl(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=di.current,C(di,m?l&1|2:l&1),St&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Mn(r),Th(),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&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&Nc(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&&V(ea),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(xi),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function pw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(xi),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Mn(r),r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Mn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return V(di),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Mn(r),Th(),n!==null&&V(ea),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(xi),null;case 25:return null;default:return null}}function Nx(n,r){switch(ph(r),r.tag){case 3:Hr(xi),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Mn(r);break;case 13:Mn(r);break;case 19:V(di);break;case 10:Hr(r.type);break;case 22:case 23:Mn(r),Th(),n!==null&&V(ea);break;case 24:Hr(xi)}}function ql(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){zt(r,r.return,k)}}function vs(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ue){zt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){zt(r,r.return,ue)}}function jx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{_g(r,l)}catch(u){zt(n,n.return,u)}}}function Tx(n,r,l){l.props=sa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){zt(n,r,u)}}function Wl(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){zt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){zt(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){zt(n,r,m)}else l.current=null}function Ax(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){zt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;Ow(u,n.type,l,r),u[O]=r}catch(m){zt(n,n.return,m)}}function Rx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ns(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Rx(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&&Ns(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 cd(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=lr));else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&Ns(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Dx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Zi(r,u,l),r[oe]=n,r[O]=l}catch(g){zt(n,n.return,g)}}var Wr=!1,vi=!1,ud=!1,Mx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function mw(n,r){if(n=n.containerInfo,Rd=Vc,n=Wm(n),nh(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 y=0,k=-1,L=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var ae;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(ae=pe.firstChild)!==null;)ee=pe,pe=ae;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(L=y),(ae=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=ae}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Vc=!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"))),Zi(g,u,l),g[oe]=n,Dt(g),u=g;break e;case"link":var y=I_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ke,Ke=y);var W=Fm(k,Ke),P=Fm(k,Ut);if(W&&P&&(ae.rangeCount!==1||ae.anchorNode!==W.node||ae.anchorOffset!==W.offset||ae.focusNode!==P.node||ae.focusOffset!==P.offset)){var Z=pe.createRange();Z.setStart(W.node,W.offset),ae.removeAllRanges(),Ke>Ut?(ae.addRange(Z),ae.extend(P.node,P.offset)):(Z.setEnd(P.node,P.offset),ae.addRange(Z))}}}}for(pe=[],ae=k;ae=ae.parentNode;)ae.nodeType===1&&pe.push({element:ae,left:ae.scrollLeft,top:ae.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=xd,xd=null;var g=Cs,y=Xr;if(ji=0,Ka=Cs=null,Xr=0,(Mt&6)!==0)throw Error(s(331));var k=Mt;if(Mt|=4,qx(g.current),Ux(g,g.current,y,l),Mt=k,Zl(0,!1),yt&&typeof yt.onPostCommitFiberRoot=="function")try{yt.onPostCommitFiberRoot(Bt,g)}catch{}return!0}finally{z.p=m,A.T=u,o_(n,r)}}function u_(n,r,l){r=Kn(l,r),r=Xh(n.stateNode,r,2),n=xs(n,r,2),n!==null&&(pt(n,2),Cr(n))}function zt(n,r,l){if(n.tag===3)u_(n,n,l);else for(;r!==null;){if(r.tag===3){u_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ws===null||!ws.has(u))){n=Kn(l,n),l=hx(2),u=xs(r,l,2),u!==null&&(dx(l,u,r,n),pt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new _w;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)||(fd=!0,m.add(l),n=ww.bind(null,n,r,l),r.then(n,n))}function ww(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(bt&l)===l&&(ai===4||ai===3&&(bt&62914560)===bt&&300>wt()-Rc?(Mt&2)===0&&Va(n,0):pd|=l,Ya===bt&&(Ya=0)),Cr(n)}function h_(n,r){r===0&&(r=Vt()),n=Vs(n,r),n!==null&&(pt(n,r),Cr(n))}function Cw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),h_(n,l)}function kw(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),h_(n,l)}function Ew(n,r){return _t(n,r)}var Pc=null,Za=null,Sd=!1,Ic=!1,wd=!1,Es=0;function Cr(n){n!==Za&&n.next===null&&(Za===null?Pc=Za=n:Za=Za.next=n),Ic=!0,Sd||(Sd=!0,jw())}function Zl(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Qe(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,m_(u,g))}else g=bt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||ft(u,g)||(l=!0,m_(u,g));u=u.next}while(l);wd=!1}}function Nw(){d_()}function d_(){Ic=Sd=!1;var n=0;Es!==0&&Pw()&&(n=Es);for(var r=wt(),l=null,u=Pc;u!==null;){var m=u.next,g=f_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Za=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}ji!==0&&ji!==5||Zl(n),Es!==0&&(Es=0)}function f_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&w_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function L_(n,r,l){var u=Qa;if(u&&typeof r=="string"&&r){var m=gi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),B_.has(m)||(B_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Zi(r,"link",n),Dt(r),u.head.appendChild(r)))}}function Yw(n){Zr.D(n),L_("dns-prefetch",n,null)}function Kw(n,r){Zr.C(n,r),L_("preconnect",n,r)}function Vw(n,r,l){Zr.L(n,r,l);var u=Qa;if(u&&n&&r){var m='link[rel="preload"][as="'+gi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+gi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+gi(l.imageSizes)+'"]')):m+='[href="'+gi(n)+'"]';var g=m;switch(r){case"style":g=Ja(n);break;case"script":g=el(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(to(g))||r==="script"&&u.querySelector(io(g))||(r=u.createElement("link"),Zi(r,"link",n),Dt(r),u.head.appendChild(r)))}}function Xw(n,r){Zr.m(n,r);var l=Qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+gi(u)+'"][href="'+gi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=el(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(io(g)))return}u=l.createElement("link"),Zi(u,"link",n),Dt(u),l.head.appendChild(u)}}}function Zw(n,r,l){Zr.S(n,r,l);var u=Qa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ja(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(to(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Id(n,l);var L=y=u.createElement("link");Dt(L),Zi(L,"link",n),L._p=new Promise(function(J,ue){L.onload=J,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Qw(n,r){Zr.X(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Dt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Jw(n,r){Zr.M(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Dt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function O_(n,r,l,u){var m=(m=le.current)?Fc(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=Ja(l.href),l=Gt(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=Ja(l.href);var g=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(to(n)))&&!g._p&&(y.instance=g,y.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||eC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=el(l),l=Gt(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 Ja(n){return'href="'+gi(n)+'"'}function to(n){return'link[rel="stylesheet"]['+n+"]"}function z_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function eC(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}),Zi(r,"link",l),Dt(r),n.head.appendChild(r))}function el(n){return'[src="'+gi(n)+'"]'}function io(n){return"script[async]"+n}function P_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+gi(l.href)+'"]');if(u)return r.instance=u,Dt(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"),Dt(u),Zi(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ja(l.href);var g=n.querySelector(to(m));if(g)return r.state.loading|=4,r.instance=g,Dt(g),g;u=z_(l),(m=er.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Dt(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Zi(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=el(l.src),(m=n.querySelector(io(g)))?(r.instance=m,Dt(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Dt(m),Zi(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function tC(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 U_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function iC(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=Ja(u.href),g=r.querySelector(to(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Dt(g);return}g=r.ownerDocument||r,u=z_(u),(m=er.get(m))&&Id(u,m),g=g.createElement("link"),Dt(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Zi(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function nC(n,r){return n.stylesheets&&n.count===0&&Kc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Kc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Kc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(rC,n),Yc=null,Gc.call(n))}function rC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=yC(),Xd.exports}var wC=SC();const CC=Pu(wC);function kC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function EC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Ry({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,N)=>fetch(E,{...N,headers:{...N==null?void 0:N.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),N=await E.json();if(!E.ok)throw new Error(N.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const N=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await N.json();if(!N.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(N){_(N instanceof Error?N.message:"Failed to switch wallet")}c(null)},j=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},D=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:D(t.address)}),d.jsx("button",{onClick:j,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Up="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 NC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,j]=w.useState("AI Writer"),[D,E]=w.useState(""),[N,I]=w.useState(""),[te,q]=w.useState(!1),[R,ie]=w.useState(null),[fe,be]=w.useState(""),[B,ne]=w.useState(null),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(null),[$,ge]=w.useState(null),T=w.useCallback((se,le)=>fetch(se,{...le,headers:{...le==null?void 0:le.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(se=>se.json()).then(se=>v(se)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(se=>se.ok?se.json():null).then(se=>{se&&ge(se)}).catch(()=>{})},[]);const M=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!D.trim()){ie("Description is required");return}q(!0),ie(null);try{const se=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:D,...N.trim()&&{genre:N}})}),le=await se.json();if(!se.ok)throw new Error(le.error||"Registration failed");v({linked:!0,agentId:le.agentId,owsWallet:le.owsWallet,txHash:le.txHash})}catch(se){ie(se instanceof Error?se.message:"Registration failed")}q(!1)},V=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}G(!0),U(null),ne(null);try{const se=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),le=await se.json();if(!se.ok)throw new Error(le.error||"Failed to generate binding code");ne(le)}catch(se){U(se instanceof Error?se.message:"Failed to generate binding code")}G(!1)},C=async(se,le)=>{await navigator.clipboard.writeText(se),z(le),setTimeout(()=>z(null),2e3)},X=async()=>{if(h(null),f(!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 se=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!se.ok){const le=await se.json();throw new Error(le.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(se){h(se instanceof Error?se.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:se=>j(se.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:D,onChange:se=>E(se.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:N,onChange:se=>I(se.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:M,disabled:te||!S.trim()||!D.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:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Up}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:se=>be(se.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"}),Y&&d.jsx("p",{className:"text-error text-xs",children:Y}),d.jsx("button",{onClick:V,disabled:F||!fe.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:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:A==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:A==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:A==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Ry,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:se=>s(se.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"}),d.jsx("input",{type:"password",value:a,onChange:se=>o(se.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:X,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 jC="http://localhost:7777";function TC({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(`${jC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const AC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},RC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function DC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),j=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),D=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(j(),S())}catch{}},[e,j,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&j()},[b,j]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ie=new Set(R);return ie.has(q)?ie.delete(q):ie.add(q),ie})},N=q=>{var ie;const R=q.map(fe=>{var be;return{file:fe.file,num:(be=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(fe=>fe.num!=null).sort((fe,be)=>parseInt(be.num)-parseInt(fe.num));return R.length>0?R[0].file:q.some(fe=>fe.file==="genesis.md")?"genesis.md":q.some(fe=>fe.file==="structure.md")?"structure.md":((ie=q[0])==null?void 0:ie.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=N(q.files);R&&s(q.name,R)}},te=q=>{const R=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...q].sort((ie,fe)=>R(ie.file)-R(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>D(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:te(q.files).map(R=>{const ie=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:RC[R.status],children:AC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var ze=Object.prototype.hasOwnProperty,_t=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Vt=e.unstable_shouldYield,ki=e.unstable_requestPaint,Ct=e.unstable_now,tt=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,je=e.unstable_NormalPriority,$e=e.unstable_LowPriority,nt=e.unstable_IdlePriority,Wt=e.log,hi=e.unstable_setDisableYieldValue,Lt=null,yt=null;function Dt(n){if(typeof Wt=="function"&&hi(n),yt&&typeof yt.setStrictMode=="function")try{yt.setStrictMode(Lt,n)}catch{}}var Qe=Math.clz32?Math.clz32:Se,di=Math.log,H=Math.LN2;function Se(n){return n>>>=0,n===0?32:31-(di(n)/H|0)|0}var Oe=256,Ae=262144,Ge=4194304;function Fe(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Fe(u):(y&=k,y!==0?m=Fe(y):l||(l=k&~n,l!==0&&(m=Fe(l))))):(k=u&~g,k!==0?m=Fe(k):y!==0?m=Fe(y):l||(l=u&~n,l!==0&&(m=Fe(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 ft(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function ct(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 Kt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ei(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function pt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function qi(n,r,l,u,m,g){var y=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,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Mi=/[\n"\\]/g;function ni(n){return n.replace(Mi,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Mr(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+St(r)):n.value!==""+St(r)&&(n.value=""+St(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?xa(n,y,St(r)):l!=null?xa(n,y,St(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=""+St(k):n.removeAttribute("name")}function Br(n,r,l,u,m,g,y,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)){_r(n);return}l=l!=null?""+St(l):"",r=r!=null?""+St(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),_r(n)}function xa(n,r,l){r==="number"&&xn(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Lr(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"),Ne=!1;if(ye)try{var Je={};Object.defineProperty(Je,"passive",{get:function(){Ne=!0}}),window.addEventListener("test",Je,Je),window.removeEventListener("test",Je,Je)}catch{Ne=!1}var Tt=null,xi=null,Yn=null;function Or(){if(Yn)return Yn;var n,r=xi,l=r.length,u,m="value"in Tt?Tt.value:Tt.textContent,g=m.length;for(n=0;n=Sl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var va=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(va)return n==="compositionend"||!Ju&&Bm(n,r)?(n=Or(),Yn=xi=Tt=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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xn(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=xn(n.document)}return r}function ih(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 Y1=ye&&"documentMode"in document&&11>=document.documentMode,ya=null,nh=null,El=null,rh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;rh||ya==null||ya!==xn(u)||(u=ya,"selectionStart"in u&&ih(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}),El&&kl(El,u)||(El=u,u=Pc(nh,"onSelect"),0>=y,m-=y,br=1<<32-Qe(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var Rt=ee(W,Ie,Z[lt],de);if(Rt===null){Ie===null&&(Ie=vt);break}n&&Ie&&Rt.alternate===null&&r(W,Ie),P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt,Ie=vt}if(lt===Z.length)return l(W,Ie),wt&&Pr(W,lt),qe;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Ts=ee(W,Ie,Rt.value,de);if(Ts===null){Ie===null&&(Ie=vt);break}n&&Ie&&Ts.alternate===null&&r(W,Ie),P=g(Ts,P,lt),At===null?qe=Ts:At.sibling=Ts,At=Ts,Ie=vt}if(Rt.done)return l(W,Ie),wt&&Pr(W,lt),qe;if(Ie===null){for(;!Rt.done;lt++,Rt=Z.next())Rt=pe(W,Rt.value,de),Rt!==null&&(P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt);return wt&&Pr(W,lt),qe}for(Ie=u(Ie);!Rt.done;lt++,Rt=Z.next())Rt=ae(Ie,W,lt,Rt.value,de),Rt!==null&&(n&&Rt.alternate!==null&&Ie.delete(Rt.key===null?lt:Rt.key),P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt);return n&&Ie.forEach(function(fC){return r(W,fC)}),wt&&Pr(W,lt),qe}function Ut(W,P,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===N&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var qe=Z.key;P!==null;){if(P.key===qe){if(qe=Z.type,qe===N){if(P.tag===7){l(W,P.sibling),de=m(P,Z.props.children),de.return=W,W=de;break e}}else if(P.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===fe&&Zs(qe)===P.type){l(W,P.sibling),de=m(P,Z.props),Dl(de,Z),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Z.type===N?(de=Gs(Z.props.children,W.mode,de,Z.key),de.return=W,W=de):(de=tc(Z.type,Z.key,Z.props,null,W.mode,de),Dl(de,Z),de.return=W,W=de)}return y(W);case S:e:{for(qe=Z.key;P!==null;){if(P.key===qe)if(P.tag===4&&P.stateNode.containerInfo===Z.containerInfo&&P.stateNode.implementation===Z.implementation){l(W,P.sibling),de=m(P,Z.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=hh(Z,W.mode,de),de.return=W,W=de}return y(W);case fe:return Z=Zs(Z),Ut(W,P,Z,de)}if(U(Z))return Be(W,P,Z,de);if(F(Z)){if(qe=F(Z),typeof qe!="function")throw Error(s(150));return Z=qe.call(Z),Ve(W,P,Z,de)}if(typeof Z.then=="function")return Ut(W,P,oc(Z),de);if(Z.$$typeof===I)return Ut(W,P,rc(W,Z),de);cc(W,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Z),de.return=W,W=de):(l(W,P),de=uh(Z,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Z,de){try{Rl=0;var qe=Ut(W,P,Z,de);return Da=null,qe}catch(Ie){if(Ie===Ra||Ie===ac)throw Ie;var At=Mn(29,Ie,null,W.mode);return At.lanes=de,At.return=W,At}finally{}}}var Js=gg(!0),xg=gg(!1),ds=!1;function wh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ch(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 fs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ps(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Bt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=ec(n),eg(n,null,l),r}return Jo(n,u,r,l),ec(n)}function Ml(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,sn(n,l)}}function kh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Eh=!1;function Bl(){if(Eh){var n=Aa;if(n!==null)throw n}}function Ll(n,r,l,u){Eh=!1;var m=n.updateQueue;ds=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=J=L=null,k=g;do{var ee=k.lane&-536870913,ae=ee!==k.lane;if(ae?(bt&ee)===ee:(u&ee)===ee){ee!==0&&ee===Ta&&(Eh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Be=n,Ve=k;ee=r;var Ut=l;switch(Ve.tag){case 1:if(Be=Ve.payload,typeof Be=="function"){pe=Be.call(Ut,pe,ee);break e}pe=Be;break e;case 3:Be.flags=Be.flags&-65537|128;case 0:if(Be=Ve.payload,ee=typeof Be=="function"?Be.call(Ut,pe,ee):Be,ee==null)break e;pe=x({},pe,ee);break e;case 2:ds=!0}}ee=k.callback,ee!==null&&(n.flags|=64,ae&&(n.flags|=8192),ae=m.callbacks,ae===null?m.callbacks=[ee]:ae.push(ee))}else ae={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=ae,L=pe):ue=ue.next=ae,y|=ee;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ae=k,k=ae.next,ae.next=null,m.lastBaseUpdate=ae,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),bs|=y,n.lanes=y,n.memoizedState=pe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Wh(n,!1,r,l);try{var L=m(),J=A.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=iw(L,u);Pl(n,r,ue,Pn(n))}else Pl(n,r,u,Pn(n))}catch(pe){Pl(n,r,{then:function(){},status:"rejected",reason:pe},Pn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function ow(){}function Fh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,$,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Pl(n,r.next.queue,{},Pn())}function qh(){return Yi(to)}function Jg(){return mi().memoizedState}function ex(){return mi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Pn();n=fs(l);var u=ps(r,n,l);u!==null&&(wn(u,r,l),Ml(u,r,l)),r={cache:bh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Pn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},bc(n)?ix(r,l):(l=oh(n,r,l,u),l!==null&&(wn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Pn();Pl(n,r,l,u)}function Pl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(bc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Dn(k,y))return Jo(n,r,m,0),Ft===null&&Qo(),!1}catch{}finally{}if(l=oh(n,r,m,u),l!==null)return wn(l,n,u),nx(l,r,u),!0}return!1}function Wh(n,r,l,u){if(u={lane:2,revertLane:wd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},bc(n)){if(r)throw Error(s(479))}else r=oh(n,l,u,2),r!==null&&wn(r,n,2)}function bc(n){var r=n.alternate;return n===st||r!==null&&r===st}function ix(n,r){Ba=dc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,sn(n,l)}}var Il={readContext:Yi,use:mc,useCallback:ai,useContext:ai,useEffect:ai,useImperativeHandle:ai,useLayoutEffect:ai,useInsertionEffect:ai,useMemo:ai,useReducer:ai,useRef:ai,useState:ai,useDebugValue:ai,useDeferredValue:ai,useTransition:ai,useSyncExternalStore:ai,useId:ai,useHostTransitionStatus:ai,useFormState:ai,useActionState:ai,useOptimistic:ai,useMemoCache:ai,useCacheRefresh:ai};Il.useEffectEvent=ai;var rx={readContext:Yi,use:mc,useCallback:function(n,r){return cn().memoizedState=[n,r===void 0?null:r],n},useContext:Yi,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,xc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return xc(4194308,4,n,r)},useInsertionEffect:function(n,r){xc(4,2,n,r)},useMemo:function(n,r){var l=cn();r=r===void 0?null:r;var u=n();if(ea){Dt(!0);try{n()}finally{Dt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=cn();if(l!==void 0){var m=l(r);if(ea){Dt(!0);try{l(r)}finally{Dt(!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=uw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=cn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ph(n);var r=n.queue,l=tx.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Uh,useDeferredValue:function(n,r){var l=cn();return $h(l,n,r)},useTransition:function(){var n=Ph(!1);return n=Xg.bind(null,st,n.queue,!0,!1),cn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=cn();if(wt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(bt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Oa(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=cn(),r=Ft.identifierPrefix;if(wt){var l=vr,u=br;l=(u&~(1<<32-Qe(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=fc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[oe]=r,g[O]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Ki(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&&qr(r)}}return Zt(r),sd(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=le.current,Na(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Gi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[oe]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||us(r,!0)}else n=Ic(n).createTextNode(u),n[oe]=r,r.stateNode=n}return Zt(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[oe]=r}else Ys(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=mh(),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 Zt(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[oe]=r}else Ys(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=mh(),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),Cc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&Nd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(K(pi),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Ul(u,!1);else{if(li!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=hc(n),g!==null){for(r.flags|=128,Ul(u,!1),n=g.updateQueue,r.updateQueue=n,Cc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(pi,pi.current&1|2),wt&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Tc&&(r.flags|=128,m=!0,Ul(u,!1),r.lanes=4194304)}else{if(!m)if(n=hc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Cc(r,n),Ul(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!wt)return Zt(r),null}else 2*Ct()-u.renderingStartTime>Tc&&l!==536870912&&(r.flags|=128,m=!0,Ul(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=Ct(),n.sibling=null,l=pi.current,C(pi,m?l&1|2:l&1),wt&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Ln(r),jh(),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&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&Cc(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&&K(Xs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(_i),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(fh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(_i),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Ln(r),r.alternate===null)throw Error(s(340));Ys()}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));Ys()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return K(pi),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Ln(r),jh(),n!==null&&K(Xs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(_i),null;case 25:return null;default:return null}}function jx(n,r){switch(fh(r),r.tag){case 3:Hr(_i),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Ln(r);break;case 13:Ln(r);break;case 19:K(pi);break;case 10:Hr(r.type);break;case 22:case 23:Ln(r),jh(),n!==null&&K(Xs);break;case 24:Hr(_i)}}function $l(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Pt(r,r.return,k)}}function xs(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ue){Pt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){Pt(r,r.return,ue)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Pt(n,n.return,u)}}}function Ax(n,r,l){l.props=ta(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Pt(n,r,u)}}function Fl(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){Pt(n,r,m)}}function yr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Pt(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){Pt(n,r,m)}else l.current=null}function Rx(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){Pt(n,n.return,m)}}function ad(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[O]=r}catch(m){Pt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Cs(n.type)||n.tag===4}function ld(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&Cs(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 od(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=Rn));else if(u!==4&&(u===27&&Cs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(od(n,r,l),n=n.sibling;n!==null;)od(n,r,l),n=n.sibling}function kc(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&&Cs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(kc(n,r,l),n=n.sibling;n!==null;)kc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Ki(r,u,l),r[oe]=n,r[O]=l}catch(g){Pt(n,n.return,g)}}var Wr=!1,yi=!1,cd=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Bi=null;function gw(n,r){if(n=n.containerInfo,Ad=Gc,n=Gm(n),ih(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 y=0,k=-1,L=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var ae;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(ae=pe.firstChild)!==null;)ee=pe,pe=ae;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(L=y),(ae=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=ae}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Rd={focusedElem:n,selectionRange:l},Gc=!1,Bi=r;Bi!==null;)if(r=Bi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Bi=n;else for(;Bi!==null;){switch(r=Bi,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"))),Ki(g,u,l),g[oe]=n,Mt(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Ut);if(W&&P&&(ae.rangeCount!==1||ae.anchorNode!==W.node||ae.anchorOffset!==W.offset||ae.focusNode!==P.node||ae.focusOffset!==P.offset)){var Z=pe.createRange();Z.setStart(W.node,W.offset),ae.removeAllRanges(),Ve>Ut?(ae.addRange(Z),ae.extend(P.node,P.offset)):(Z.setEnd(P.node,P.offset),ae.addRange(Z))}}}}for(pe=[],ae=k;ae=ae.parentNode;)ae.nodeType===1&&pe.push({element:ae,left:ae.scrollLeft,top:ae.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=gd,gd=null;var g=ys,y=Xr;if(ji=0,Ua=ys=null,Xr=0,(Bt&6)!==0)throw Error(s(331));var k=Bt;if(Bt|=4,Wx(g.current),$x(g,g.current,y,l),Bt=k,Kl(0,!1),yt&&typeof yt.onPostCommitFiberRoot=="function")try{yt.onPostCommitFiberRoot(Lt,g)}catch{}return!0}finally{z.p=m,A.T=u,c_(n,r)}}function h_(n,r,l){r=Xn(l,r),r=Kh(n.stateNode,r,2),n=ps(n,r,2),n!==null&&(pt(n,2),Sr(n))}function Pt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(vs===null||!vs.has(u))){n=Xn(l,n),l=dx(2),u=ps(r,l,2),u!==null&&(fx(l,u,r,n),pt(u,2),Sr(u));break}}r=r.return}}function vd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(dd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(bt&l)===l&&(li===4||li===3&&(bt&62914560)===bt&&300>Ct()-jc?(Bt&2)===0&&$a(n,0):fd|=l,Ha===bt&&(Ha=0)),Sr(n)}function d_(n,r){r===0&&(r=Kt()),n=Ws(n,r),n!==null&&(pt(n,r),Sr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return _t(n,r)}var Lc=null,qa=null,yd=!1,Oc=!1,Sd=!1,ws=0;function Sr(n){n!==qa&&n.next===null&&(qa===null?Lc=qa=n:qa=qa.next=n),Oc=!0,yd||(yd=!0,Tw())}function Kl(n,r){if(!Sd&&Oc){Sd=!0;do for(var l=!1,u=Lc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Qe(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=bt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||ft(u,g)||(l=!0,g_(u,g));u=u.next}while(l);Sd=!1}}function jw(){f_()}function f_(){Oc=yd=!1;var n=0;ws!==0&&Iw()&&(n=ws);for(var r=Ct(),l=null,u=Lc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Lc=m:l.next=m,m===null&&(qa=l)):(l=u,(n!==0||(g&3)!==0)&&(Oc=!0)),u=m}ji!==0&&ji!==5||Kl(n),ws!==0&&(ws=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&C_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function O_(n,r,l){var u=Wa;if(u&&typeof r=="string"&&r){var m=ni(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Ki(r,"link",n),Mt(r),u.head.appendChild(r)))}}function Vw(n){Zr.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){Zr.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){Zr.L(n,r,l);var u=Wa;if(u&&n&&r){var m='link[rel="preload"][as="'+ni(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+ni(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+ni(l.imageSizes)+'"]')):m+='[href="'+ni(n)+'"]';var g=m;switch(r){case"style":g=Ga(n);break;case"script":g=Ya(n)}ir.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),ir.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(Jl(g))||r==="script"&&u.querySelector(eo(g))||(r=u.createElement("link"),Ki(r,"link",n),Mt(r),u.head.appendChild(r)))}}function Zw(n,r){Zr.m(n,r);var l=Wa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+ni(u)+'"][href="'+ni(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ya(n)}if(!ir.has(g)&&(n=x({rel:"modulepreload",href:n},r),ir.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(eo(g)))return}u=l.createElement("link"),Ki(u,"link",n),Mt(u),l.head.appendChild(u)}}}function Qw(n,r,l){Zr.S(n,r,l);var u=Wa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ga(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(Jl(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=ir.get(g))&&Pd(n,l);var L=y=u.createElement("link");Mt(L),Ki(L,"link",n),L._p=new Promise(function(J,ue){L.onload=J,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Uc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){Zr.X(n,r);var l=Wa;if(l&&n){var u=Gt(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(eo(m)),g||(n=x({src:n,async:!0},r),(r=ir.get(m))&&Id(n,r),g=l.createElement("script"),Mt(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){Zr.M(n,r);var l=Wa;if(l&&n){var u=Gt(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(eo(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=ir.get(m))&&Id(n,r),g=l.createElement("script"),Mt(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=le.current)?Hc(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=Gt(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=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(Jl(n)))&&!g._p&&(y.instance=g,y.state.loading=5),ir.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},ir.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Gt(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="'+ni(n)+'"'}function Jl(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),Ki(r,"link",l),Mt(r),n.head.appendChild(r))}function Ya(n){return'[src="'+ni(n)+'"]'}function eo(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+ni(l.href)+'"]');if(u)return r.instance=u,Mt(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"),Mt(u),Ki(u,"style",m),Uc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ga(l.href);var g=n.querySelector(Jl(m));if(g)return r.state.loading|=4,r.instance=g,Mt(g),g;u=P_(l),(m=ir.get(m))&&Pd(u,m),g=(n.ownerDocument||n).createElement("link"),Mt(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ki(g,"link",u),r.state.loading|=4,Uc(g,l.precedence,n),r.instance=g;case"script":return g=Ya(l.src),(m=n.querySelector(eo(g)))?(r.instance=m,Mt(m),m):(u=l,(m=ir.get(g))&&(u=x({},l),Id(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Mt(m),Ki(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,Uc(u,l.precedence,n));return r.instance}function Uc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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(Jl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Fc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Mt(g);return}g=r.ownerDocument||r,u=P_(u),(m=ir.get(m))&&Pd(u,m),g=g.createElement("link"),Mt(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ki(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=Fc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Hd=0;function rC(n,r){return n.stylesheets&&n.count===0&&Wc(n,n.stylesheets),0Hd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Fc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var qc=null;function Wc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,qc=new Map,r.forEach(sC,n),qc=null,Fc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=qc.get(n);if(l)var u=l.get(null);else{l=new Map,qc.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(),Kd.exports=SC(),Kd.exports}var CC=wC();const kC=Lu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 Jd="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,j)=>fetch(E,{...j,headers:{...j==null?void 0:j.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Jd}/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(`${Jd}/api/wallet/create`,{method:"POST"}),j=await E.json();if(!E.ok)throw new Error(j.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const j=await x(`${Jd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await j.json();if(!j.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(j){_(j instanceof Error?j.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 wu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const $p="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[j,I]=w.useState(""),[te,q]=w.useState(!1),[R,ie]=w.useState(null),[fe,be]=w.useState(""),[B,ne]=w.useState(null),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(null),[$,ge]=w.useState(null),T=w.useCallback((re,le)=>fetch(re,{...le,headers:{...le==null?void 0:le.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(re=>re.json()).then(re=>v(re)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(re=>re.ok?re.json():null).then(re=>{re&&ge(re)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!M.trim()){ie("Description is required");return}q(!0),ie(null);try{const re=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...j.trim()&&{genre:j}})}),le=await re.json();if(!re.ok)throw new Error(le.error||"Registration failed");v({linked:!0,agentId:le.agentId,owsWallet:le.owsWallet,txHash:le.txHash})}catch(re){ie(re instanceof Error?re.message:"Registration failed")}q(!1)},K=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}G(!0),U(null),ne(null);try{const re=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),le=await re.json();if(!re.ok)throw new Error(le.error||"Failed to generate binding code");ne(le)}catch(re){U(re instanceof Error?re.message:"Failed to generate binding code")}G(!1)},C=async(re,le)=>{await navigator.clipboard.writeText(re),z(le),setTimeout(()=>z(null),2e3)},X=async()=>{if(h(null),f(!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 re=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!re.ok){const le=await re.json();throw new Error(le.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(re){h(re instanceof Error?re.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:re=>N(re.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:re=>E(re.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:j,onChange:re=>I(re.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:te||!S.trim()||!M.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:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),wu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:$p}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:re=>be(re.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"}),Y&&d.jsx("p",{className:"text-error text-xs",children:Y}),d.jsx("button",{onClick:K,disabled:F||!fe.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:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:A==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:A==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:A==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:re=>s(re.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"}),d.jsx("input",{type:"password",value:a,onChange:re=>o(re.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:X,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ie=new Set(R);return ie.has(q)?ie.delete(q):ie.add(q),ie})},j=q=>{var ie;const R=q.map(fe=>{var be;return{file:fe.file,num:(be=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(fe=>fe.num!=null).sort((fe,be)=>parseInt(be.num)-parseInt(fe.num));return R.length>0?R[0].file:q.some(fe=>fe.file==="genesis.md")?"genesis.md":q.some(fe=>fe.file==="structure.md")?"structure.md":((ie=q[0])==null?void 0:ie.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=j(q.files);R&&s(q.name,R)}},te=q=>{const R=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...q].sort((ie,fe)=>R(ie.file)-R(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:te(q.files).map(R=>{const ie=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.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 Dy=Object.defineProperty,MC=Object.getOwnPropertyDescriptor,BC=(e,t)=>{for(var i in t)Dy(e,i,{get:t[i],enumerable:!0})},ci=(e,t,i,s)=>{for(var a=s>1?void 0:s?MC(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&&Dy(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),hb="Terminal input",Uf={get:()=>hb,set:e=>hb=e},db="Too much output to announce, navigate to rows manually to read",$f={get:()=>db,set:e=>db=e};function LC(e){return e.replace(/\r?\n/g,"\r")}function OC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function zC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function PC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");My(a,t,i,s)}}function My(e,t,i,s){e=LC(e),e=OC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function By(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 fb(e,t,i,s,a){By(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function zs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 IC=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}},HC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,j;for(;(j=this.interim[++S]&63)&&S<4;)v<<=6,v|=j;let D=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=D-S;for(;f=i)return 0;if(j=e[f++],(j&192)!==128){f--,b=!0;break}else this.interim[S++]=j,v<<=6,v|=j&63}b||(D===2?v<128?f--:t[s++]=v:D===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=f;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}},Ly="",Is=" ",Ho=class Oy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 Oy;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}},Nu=class zy{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 zy(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Py extends Ho{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Py;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?zs(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()]}},pb="di$target",Ff="di$dependencies",tf=new Map;function UC(e){return e[Ff]||[]}function $i(e){if(tf.has(e))return tf.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");$C(t,i,a)};return t._id=e,tf.set(e,t),t}function $C(e,t,i){t[pb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[pb]=t)}var mn=$i("BufferService"),Iy=$i("CoreMouseService"),ba=$i("CoreService"),FC=$i("CharsetService"),$p=$i("InstantiationService"),Hy=$i("LogService"),gn=$i("OptionsService"),Uy=$i("OscLinkService"),qC=$i("UnicodeService"),Uo=$i("DecorationService"),qf=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,f=!1;for(let x=0;xa?a.activate(j,D,v):WC(j,D),hover:(j,D)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,j,D,v)},leave:(j,D)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,j,D,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=ci([Re(0,mn),Re(1,gn),Re(2,Uy)],qf);function WC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},ui=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Hf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",Uf={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Bs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ou(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",Os=" ",Po=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Cu}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 zy;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}},Cu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},lr=class Iy extends Po{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Cu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Bs(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()]}},mb="di$target",$f="di$dependencies",ef=new Map;function $C(e){return e[$f]||[]}function Fi(e){if(ef.has(e))return ef.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");FC(t,i,a)};return t._id=e,ef.set(e,t),t}function FC(e,t,i){t[mb]===t?t[$f].push({id:e,index:i}):(t[$f]=[{id:e,index:i}],t[mb]=t)}var pn=Fi("BufferService"),Hy=Fi("CoreMouseService"),ma=Fi("CoreService"),qC=Fi("CharsetService"),Fp=Fi("InstantiationService"),Uy=Fi("LogService"),mn=Fi("OptionsService"),$y=Fi("OscLinkService"),WC=Fi("UnicodeService"),Io=Fi("DecorationService"),Ff=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 lr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Ff=ui([Re(0,pn),Re(1,mn),Re(2,$y)],Ff);function GC(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 Hu=$i("CharSizeService"),ns=$i("CoreBrowserService"),Fp=$i("MouseService"),rs=$i("RenderService"),GC=$i("SelectionService"),$y=$i("CharacterJoinerService"),xl=$i("ThemeService"),Fy=$i("LinkProviderService"),YC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?mb.isErrorNoTelemetry(e)?new mb(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 zu=Fi("CharSizeService"),ns=Fi("CoreBrowserService"),qp=Fi("MouseService"),rs=Fi("RenderService"),YC=Fi("SelectionService"),Fy=Fi("CharacterJoinerService"),ul=Fi("ThemeService"),qy=Fi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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)}},KC=new YC;function gu(e){VC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function VC(e){return e instanceof XC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var XC=class extends Error{constructor(){super(Wf),this.name=this.message}};function ZC(e){return new Error(`Illegal argument: ${e}`)}var mb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class qy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,qy.prototype)}};function zn(e,t=0){return e[e.length-(1+t)]}var QC;(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})(QC||(QC={}));function JC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Wy;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let q=te.length-1;q>=0;q--)yield te[q]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,q){let R=0;for(let ie of te)if(q(ie,R++))return!0;return!1}e.some=_;function x(te,q){for(let R of te)if(q(R))return R}e.find=x;function*b(te,q){for(let R of te)q(R)&&(yield R)}e.filter=b;function*v(te,q){let R=0;for(let ie of te)yield q(ie,R++)}e.map=v;function*S(te,q){let R=0;for(let ie of te)yield*q(ie,R++)}e.flatMap=S;function*j(...te){for(let q of te)yield*q}e.concat=j;function D(te,q,R){let ie=R;for(let fe of te)ie=q(ie,fe);return ie}e.reduce=D;function*E(te,q,R=te.length){for(q<0&&(q+=te.length),R<0?R+=te.length:R>te.length&&(R=te.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 ek(...e){return ii(()=>ga(e))}function ii(e){return{dispose:JC(()=>{e()})}}var Gy=class Yy{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{ga(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?Yy.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)}};Gy.DISABLE_DISPOSED_WARNING=!1;var Hs=Gy,ht=class{constructor(){this._store=new Hs,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)}};ht.None=Object.freeze({dispose(){}});var pl=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}},is=typeof window=="object"?window:globalThis,Kf=class Vf{constructor(t){this.element=t,this.next=Vf.Undefined,this.prev=Vf.Undefined}};Kf.Undefined=new Kf(void 0);var ni=Kf,gb=class{constructor(){this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ni.Undefined}clear(){let e=this._first;for(;e!==ni.Undefined;){let t=e.next;e.prev=ni.Undefined,e.next=ni.Undefined,e=t}this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ni(e);if(this._first===ni.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!==ni.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ni.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ni.Undefined&&e.next!==ni.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ni.Undefined&&e.next===ni.Undefined?(this._first=ni.Undefined,this._last=ni.Undefined):e.next===ni.Undefined?(this._last=this._last.prev,this._last.next=ni.Undefined):e.prev===ni.Undefined&&(this._first=this._first.next,this._first.prev=ni.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ni.Undefined;)yield e.element,e=e.next}},tk=globalThis.performance&&typeof globalThis.performance.now=="function",ik=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=tk&&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}},en;(e=>{e.None=()=>ht.None;function t(F,G){return x(F,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(F){return(G,Y=null,U)=>{let A=!1,z;return z=F($=>{if(!A)return z?z.dispose():A=!0,G.call(Y,$)},null,U),A&&z.dispose(),z}}e.once=i;function s(F,G,Y){return f((U,A=null,z)=>F($=>U.call(A,G($)),null,z),Y)}e.map=s;function a(F,G,Y){return f((U,A=null,z)=>F($=>{G($),U.call(A,$)},null,z),Y)}e.forEach=a;function o(F,G,Y){return f((U,A=null,z)=>F($=>G($)&&U.call(A,$),null,z),Y)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(G,Y=null,U)=>{let A=ek(...F.map(z=>z($=>G.call(Y,$))));return _(A,U)}}e.any=h;function p(F,G,Y,U){let A=Y;return s(F,z=>(A=G(A,z),A),U)}e.reduce=p;function f(F,G){let Y,U={onWillAddFirstListener(){Y=F(A.fire,A)},onDidRemoveLastListener(){Y==null||Y.dispose()}},A=new we(U);return G==null||G.add(A),A.event}function _(F,G){return G instanceof Array?G.push(F):G&&G.add(F),F}function x(F,G,Y=100,U=!1,A=!1,z,$){let ge,T,M,V=0,C,X={leakWarningThreshold:z,onWillAddFirstListener(){ge=F(le=>{V++,T=G(T,le),U&&!M&&(se.fire(T),T=void 0),C=()=>{let K=T;T=void 0,M=void 0,(!U||V>1)&&se.fire(K),V=0},typeof Y=="number"?(clearTimeout(M),M=setTimeout(C,Y)):M===void 0&&(M=0,queueMicrotask(C))})},onWillRemoveListener(){A&&V>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,ge.dispose()}},se=new we(X);return $==null||$.add(se),se.event}e.debounce=x;function b(F,G=0,Y){return e.debounce(F,(U,A)=>U?(U.push(A),U):[A],G,void 0,!0,void 0,Y)}e.accumulate=b;function v(F,G=(U,A)=>U===A,Y){let U=!0,A;return o(F,z=>{let $=U||!G(z,A);return U=!1,A=z,$},Y)}e.latch=v;function S(F,G,Y){return[e.filter(F,G,Y),e.filter(F,U=>!G(U),Y)]}e.split=S;function j(F,G=!1,Y=[],U){let A=Y.slice(),z=F(T=>{A?A.push(T):ge.fire(T)});U&&U.add(z);let $=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new we({onWillAddFirstListener(){z||(z=F(T=>ge.fire(T)),U&&U.add(z))},onDidAddFirstListener(){A&&(G?setTimeout($):$())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(ge),ge.event}e.buffer=j;function D(F,G){return(Y,U,A)=>{let z=G(new N);return F(function($){let ge=z.evaluate($);ge!==E&&Y.call(U,ge)},void 0,A)}}e.chain=D;let E=Symbol("HaltChainable");class N{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(Y=>(G(Y),Y)),this}filter(G){return this.steps.push(Y=>G(Y)?Y:E),this}reduce(G,Y){let U=Y;return this.steps.push(A=>(U=G(U,A),U)),this}latch(G=(Y,U)=>Y===U){let Y=!0,U;return this.steps.push(A=>{let z=Y||!G(A,U);return Y=!1,U=A,z?A:E}),this}evaluate(G){for(let Y of this.steps)if(G=Y(G),G===E)break;return G}}function I(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.on(G,U),z=()=>F.removeListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromNodeEventEmitter=I;function te(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.addEventListener(G,U),z=()=>F.removeEventListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromDOMEventEmitter=te;function q(F){return new Promise(G=>i(F)(G))}e.toPromise=q;function R(F){let G=new we;return F.then(Y=>{G.fire(Y)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ie(F,G){return F(Y=>G.fire(Y))}e.forward=ie;function fe(F,G,Y){return G(Y),F(U=>G(U))}e.runAndSubscribe=fe;class be{constructor(G,Y){this._observable=G,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new we(U),Y&&Y.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,Y){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 B(F,G){return new be(F,G).emitter.event}e.fromObservable=B;function ne(F){return(G,Y,U)=>{let A=0,z=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(F.reportChanges(),z&&(z=!1,G.call(Y)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver($),F.reportChanges();let ge={dispose(){F.removeObserver($)}};return U instanceof Hs?U.add(ge):Array.isArray(U)&&U.push(ge),ge}}e.fromObservableLight=ne})(en||(en={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new ik,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}}};Xf.all=new Set,Xf._idPool=0;var nk=Xf,rk=-1,Vy=class Xy{constructor(t,i,s=(Xy._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)}},KC=new VC;function fu(e){XC(e)||KC.onUnexpectedError(e)}var qf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===qf&&e.message===qf}var ZC=class extends Error{constructor(){super(qf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Wf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Wf)return t;let i=new Wf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Gf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function In(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let q=te.length-1;q>=0;q--)yield te[q]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,q){let R=0;for(let ie of te)if(q(ie,R++))return!0;return!1}e.some=_;function x(te,q){for(let R of te)if(q(R))return R}e.find=x;function*b(te,q){for(let R of te)q(R)&&(yield R)}e.filter=b;function*v(te,q){let R=0;for(let ie of te)yield q(ie,R++)}e.map=v;function*S(te,q){let R=0;for(let ie of te)yield*q(ie,R++)}e.flatMap=S;function*N(...te){for(let q of te)yield*q}e.concat=N;function M(te,q,R){let ie=R;for(let fe of te)ie=q(ie,fe);return ie}e.reduce=M;function*E(te,q,R=te.length){for(q<0&&(q+=te.length),R<0?R+=te.length:R>te.length&&(R=te.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 tk(...e){return ii(()=>da(e))}function ii(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{da(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var zs=Yy,ht=class{constructor(){this._store=new zs,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)}};ht.None=Object.freeze({dispose(){}});var ll=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}},is=typeof window=="object"?window:globalThis,Yf=class Vf{constructor(t){this.element=t,this.next=Vf.Undefined,this.prev=Vf.Undefined}};Yf.Undefined=new Yf(void 0);var ri=Yf,xb=class{constructor(){this._first=ri.Undefined,this._last=ri.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ri.Undefined}clear(){let e=this._first;for(;e!==ri.Undefined;){let t=e.next;e.prev=ri.Undefined,e.next=ri.Undefined,e=t}this._first=ri.Undefined,this._last=ri.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ri(e);if(this._first===ri.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!==ri.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ri.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ri.Undefined&&e.next!==ri.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ri.Undefined&&e.next===ri.Undefined?(this._first=ri.Undefined,this._last=ri.Undefined):e.next===ri.Undefined?(this._last=this._last.prev,this._last.next=ri.Undefined):e.prev===ri.Undefined&&(this._first=this._first.next,this._first.prev=ri.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ri.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},Qi;(e=>{e.None=()=>ht.None;function t(F,G){return x(F,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(F){return(G,Y=null,U)=>{let A=!1,z;return z=F($=>{if(!A)return z?z.dispose():A=!0,G.call(Y,$)},null,U),A&&z.dispose(),z}}e.once=i;function s(F,G,Y){return f((U,A=null,z)=>F($=>U.call(A,G($)),null,z),Y)}e.map=s;function a(F,G,Y){return f((U,A=null,z)=>F($=>{G($),U.call(A,$)},null,z),Y)}e.forEach=a;function o(F,G,Y){return f((U,A=null,z)=>F($=>G($)&&U.call(A,$),null,z),Y)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(G,Y=null,U)=>{let A=tk(...F.map(z=>z($=>G.call(Y,$))));return _(A,U)}}e.any=h;function p(F,G,Y,U){let A=Y;return s(F,z=>(A=G(A,z),A),U)}e.reduce=p;function f(F,G){let Y,U={onWillAddFirstListener(){Y=F(A.fire,A)},onDidRemoveLastListener(){Y==null||Y.dispose()}},A=new we(U);return G==null||G.add(A),A.event}function _(F,G){return G instanceof Array?G.push(F):G&&G.add(F),F}function x(F,G,Y=100,U=!1,A=!1,z,$){let ge,T,D,K=0,C,X={leakWarningThreshold:z,onWillAddFirstListener(){ge=F(le=>{K++,T=G(T,le),U&&!D&&(re.fire(T),T=void 0),C=()=>{let V=T;T=void 0,D=void 0,(!U||K>1)&&re.fire(V),K=0},typeof Y=="number"?(clearTimeout(D),D=setTimeout(C,Y)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){A&&K>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,ge.dispose()}},re=new we(X);return $==null||$.add(re),re.event}e.debounce=x;function b(F,G=0,Y){return e.debounce(F,(U,A)=>U?(U.push(A),U):[A],G,void 0,!0,void 0,Y)}e.accumulate=b;function v(F,G=(U,A)=>U===A,Y){let U=!0,A;return o(F,z=>{let $=U||!G(z,A);return U=!1,A=z,$},Y)}e.latch=v;function S(F,G,Y){return[e.filter(F,G,Y),e.filter(F,U=>!G(U),Y)]}e.split=S;function N(F,G=!1,Y=[],U){let A=Y.slice(),z=F(T=>{A?A.push(T):ge.fire(T)});U&&U.add(z);let $=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new we({onWillAddFirstListener(){z||(z=F(T=>ge.fire(T)),U&&U.add(z))},onDidAddFirstListener(){A&&(G?setTimeout($):$())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(ge),ge.event}e.buffer=N;function M(F,G){return(Y,U,A)=>{let z=G(new j);return F(function($){let ge=z.evaluate($);ge!==E&&Y.call(U,ge)},void 0,A)}}e.chain=M;let E=Symbol("HaltChainable");class j{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(Y=>(G(Y),Y)),this}filter(G){return this.steps.push(Y=>G(Y)?Y:E),this}reduce(G,Y){let U=Y;return this.steps.push(A=>(U=G(U,A),U)),this}latch(G=(Y,U)=>Y===U){let Y=!0,U;return this.steps.push(A=>{let z=Y||!G(A,U);return Y=!1,U=A,z?A:E}),this}evaluate(G){for(let Y of this.steps)if(G=Y(G),G===E)break;return G}}function I(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.on(G,U),z=()=>F.removeListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromNodeEventEmitter=I;function te(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.addEventListener(G,U),z=()=>F.removeEventListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromDOMEventEmitter=te;function q(F){return new Promise(G=>i(F)(G))}e.toPromise=q;function R(F){let G=new we;return F.then(Y=>{G.fire(Y)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ie(F,G){return F(Y=>G.fire(Y))}e.forward=ie;function fe(F,G,Y){return G(Y),F(U=>G(U))}e.runAndSubscribe=fe;class be{constructor(G,Y){this._observable=G,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new we(U),Y&&Y.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,Y){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 B(F,G){return new be(F,G).emitter.event}e.fromObservable=B;function ne(F){return(G,Y,U)=>{let A=0,z=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(F.reportChanges(),z&&(z=!1,G.call(Y)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver($),F.reportChanges();let ge={dispose(){F.removeObserver($)}};return U instanceof zs?U.add(ge):Array.isArray(U)&&U.push(ge),ge}}e.fromObservableLight=ne})(Qi||(Qi={}));var Kf=class Xf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Xf._idPool++}`,Xf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Kf.all=new Set,Kf._idPool=0;var rk=Kf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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,f,_,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],S=new ok(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=ak.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new dk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof Hs?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*uk<=i.length){let f=0;for(let _=0;_0}},dk=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}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new we,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new we,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}};Qf.INSTANCE=new Qf;var qp=Qf;function fk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}qp.INSTANCE.onDidChangeZoomLevel;function pk(e){return qp.INSTANCE.getZoomFactor(e)}qp.INSTANCE.onDidChangeFullscreen;var _l=typeof navigator=="object"?navigator.userAgent:"",Jf=_l.indexOf("Firefox")>=0,mk=_l.indexOf("AppleWebKit")>=0,Wp=_l.indexOf("Chrome")>=0,gk=!Wp&&_l.indexOf("Safari")>=0;_l.indexOf("Electron/")>=0;_l.indexOf("Android")>=0;var rf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");rf=e.matches,fk(is,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var cl="en",ep=!1,tp=!1,xu=!1,Qy=!1,iu,_u=cl,xb=cl,xk,dr,ma=globalThis,Ji,jy;typeof ma.vscode<"u"&&typeof ma.vscode.process<"u"?Ji=ma.vscode.process:typeof process<"u"&&typeof((jy=process==null?void 0:process.versions)==null?void 0:jy.node)=="string"&&(Ji=process);var Ty,_k=typeof((Ty=Ji==null?void 0:Ji.versions)==null?void 0:Ty.electron)=="string",bk=_k&&(Ji==null?void 0:Ji.type)==="renderer",Ay;if(typeof Ji=="object"){ep=Ji.platform==="win32",tp=Ji.platform==="darwin",xu=Ji.platform==="linux",xu&&Ji.env.SNAP&&Ji.env.SNAP_REVISION,Ji.env.CI||Ji.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=cl,_u=cl;let e=Ji.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,xb=t.osLocale,_u=t.resolvedLanguage||cl,xk=(Ay=t.languagePack)==null?void 0:Ay.translationsConfigFile}catch{}Qy=!0}else typeof navigator=="object"&&!bk?(dr=navigator.userAgent,ep=dr.indexOf("Windows")>=0,tp=dr.indexOf("Macintosh")>=0,(dr.indexOf("Macintosh")>=0||dr.indexOf("iPad")>=0||dr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=dr.indexOf("Linux")>=0,(dr==null?void 0:dr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||cl,iu=navigator.language.toLowerCase(),xb=iu):console.error("Unable to resolve platform.");var Jy=ep,Rr=tp,vk=xu,_b=Qy,Dr=dr,Ms=_u,yk;(e=>{function t(){return Ms}e.value=t;function i(){return Ms.length===2?Ms==="en":Ms.length>=3?Ms[0]==="e"&&Ms[1]==="n"&&Ms[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ms==="en"}e.isDefault=s})(yk||(yk={}));var Sk=typeof ma.postMessage=="function"&&!ma.importScripts;(()=>{if(Sk){let e=[];ma.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}),ma.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var wk=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!wk&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var il=typeof navigator=="object"?navigator:{};_b||document.queryCommandSupported&&document.queryCommandSupported("copy")||il&&il.clipboard&&il.clipboard.writeText,_b||il&&il.clipboard&&il.clipboard.readText;var Gp=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}},sf=new Gp,bb=new Gp,vb=new Gp,Ck=new Array(230),e0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return bb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return vb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return bb.strToKeyCode(h)||vb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(e0||(e0={}));var kk=class t0{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 t0&&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 Ek([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ek=class{constructor(e){if(e.length===0)throw ZC("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 Lk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:en.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:i0})})(Bk||(Bk={}));var Lk=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?i0:(this._emitter||(this._emitter=new we),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Yp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Ok=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},zk;(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})(zk||(zk={}));var Cb=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 we,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())}};Cb.EMPTY=Cb.fromArray([]);var{getWindow:Tr,getWindowId:Pk,onDidRegisterWindow:Ik}=(function(){let e=new Map,t={window:is,disposables:new Hs};e.set(is.vscodeWindowId,t);let i=new we,s=new we,a=new we;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 ht.None;let h=new Hs,p={window:c,disposables:h.add(new Hs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ze(c,Bi.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Tr(c).document}}})(),Hk=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 Ze(e,t,i,s){return new Hk(e,t,i,s)}var kb=function(e,t,i,s){return Ze(e,t,i,s)},Kp,Uk=class extends Ok{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Eb=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){gu(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(Eb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Pk(o),f=new Eb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function $k(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Bi={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"},Fk=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=wn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=wn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=wn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=wn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=wn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=wn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=wn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=wn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=wn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=wn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=wn(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=wn(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=wn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=wn(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 wn(e){return typeof e=="number"?`${e}px`:e}function jo(e){return new Fk(e)}var n0=class{constructor(){this._hooks=new Hs,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(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ze(o,Bi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ze(o,Bi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function qk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var yo=class nn extends ht{constructor(){super(),this.dispatched=!1,this.targets=new gb,this.ignoreTargets=new gb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(en.runAndSubscribe(Ik,({window:t,disposables:i})=>{i.add(Ze(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ze(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ze(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!nn.isTouchDevice())return ht.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!nn.isTouchDevice())return ht.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||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=nn.HOLD_DELAY&&Math.abs(p.initialPageX-zn(p.rollingPageX))<30&&Math.abs(p.initialPageY-zn(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=zn(p.rollingPageX),_.pageY=zn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=zn(p.rollingPageX),x=zn(p.rollingPageY),b=zn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],j=[...this.targets].filter(D=>p.initialTarget instanceof Node&&D.contains(p.initialTarget));this.inertia(t,j,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>nn.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=nn.SCROLL_FRICTION*x,h+=nn.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let j=this.newGestureEvent(Nr.Change);j.translationX=b,j.translationY=v,i.forEach(D=>D.dispatchEvent(j)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};yo.SCROLL_FRICTION=-.005,yo.HOLD_DELAY=700,yo.CLEAR_TAP_COUNT_TIME=400,ci([qk],yo,"isTouchDevice",1);var Wk=yo,Vp=class extends ht{onclick(e,t){this._register(Ze(e,Bi.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ze(e,Bi.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ze(e,Bi.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ze(e,Bi.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ze(e,Bi.KEY_DOWN,i=>t(new yb(i))))}onkeyup(e,t){this._register(Ze(e,Bi.KEY_UP,i=>t(new yb(i))))}oninput(e,t){this._register(Ze(e,Bi.INPUT,t))}onblur(e,t){this._register(Ze(e,Bi.BLUR,t))}onfocus(e,t){this._register(Ze(e,Bi.FOCUS,t))}onchange(e,t){this._register(Ze(e,Bi.CHANGE,t))}ignoreGesture(e){return Wk.ignoreTarget(e)}},Nb=11,Gk=class extends Vp{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=Nb+"px",this.domNode.style.height=Nb+"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 n0),this._register(kb(this.bgDomNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(kb(this.domNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Uk),this._pointerdownScheduleRepeatTimer=this._register(new Yp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Yk=class ip{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 ip(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 ip(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}}},Kk=class extends ht{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Yk(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 Tb(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=Tb.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)))}},jb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Zk(s)}}function Vk(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":"")))}},Jk=140,r0=class extends Vp{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 Qk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new n0),this._shouldRender=!0,this.domNode=jo(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(Ze(this.domNode.domNode,Bi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Gk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=jo(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(Ze(this.slider.domNode,Bi.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=$k(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(Jy&&c>Jk){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()}},s0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var r2=sp,s2=class extends Vp{constructor(e,t,i){super(),this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new we),this.onWillScroll=this._onWillScroll.event,this._options=l2(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 t2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new e2(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=jo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=jo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=jo(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 Yp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ga(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,Rr&&(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 wb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ga(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new wb(i))};this._mouseWheelToDispose.push(Ze(this._listenOnDomNode,Bi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=r2.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=!Rr&&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(),f={};if(o){let _=Ab*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Ab*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),i2)}},a2=class extends s2{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 l2(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,Rr&&(t.className+=" mac"),t}var ap=class extends ht{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new a2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(en.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(f=>this._handleScroll(f)))}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}};ap=ci([Re(2,mn),Re(3,ns),Re(4,Iy),Re(5,xl),Re(6,gn),Re(7,rs)],ap);var lp=class extends ht{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(ii(()=>{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()}};lp=ci([Re(1,mn),Re(2,ns),Re(3,Uo),Re(4,rs)],lp);var o2=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)}},kr={full:0,left:0,center:0,right:0},Bs={full:0,left:0,center:0,right:0},co={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 o2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{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);Bs.full=this._canvas.width,Bs.left=e,Bs.center=t,Bs.right=e,this._refreshDrawHeightConstants(),co.full=1,co.left=1,co.center=1+Bs.left,co.right=1+Bs.left+Bs.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(co[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Bs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=ci([Re(2,mn),Re(3,Uo),Re(4,rs),Re(5,gn),Re(6,xl),Re(7,ns)],ju);var me;(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=""))(me||(me={}));var bu;(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="Ÿ"))(bu||(bu={}));var a0;(e=>e.ST=`${me.ESC}\\`)(a0||(a0={}));var op=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)}}};op=ci([Re(2,mn),Re(3,gn),Re(4,ba),Re(5,rs)],op);var Li=0,Oi=0,zi=0,li=0,Rb={css:"#00000000",rgba:0},wi;(e=>{function t(a,o,c,h){return h!==void 0?`#${oa(a)}${oa(o)}${oa(c)}${oa(h)}`:`#${oa(a)}${oa(o)}${oa(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 Qt;(e=>{function t(p,f){if(li=(f.rgba&255)/255,li===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Li=v+Math.round((_-v)*li),Oi=S+Math.round((x-S)*li),zi=j+Math.round((b-j)*li);let D=wi.toCss(Li,Oi,zi),E=wi.toRgba(Li,Oi,zi);return{css:D,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return wi.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Li,Oi,zi]=vu.toChannels(f),{css:wi.toCss(Li,Oi,zi),rgba:f}}e.opaque=a;function o(p,f){return li=Math.round(f*255),[Li,Oi,zi]=vu.toChannels(p.rgba),{css:wi.toCss(Li,Oi,zi,li),rgba:wi.toRgba(Li,Oi,zi,li)}}e.opacity=o;function c(p,f){return li=p.rgba&255,o(p,li*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var ri;(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 Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),wi.toColor(Li,Oi,zi);case 5:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),wi.toColor(Li,Oi,zi,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 Li=parseInt(o[1]),Oi=parseInt(o[2]),zi=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),wi.toColor(Li,Oi,zi,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),[Li,Oi,zi,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:wi.toRgba(Li,Oi,zi,li),css:a}}e.toColor=s})(ri||(ri={}));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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var vu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Li=x+Math.round((p-x)*li),Oi=b+Math.round((f-b)*li),zi=v+Math.round((_-v)*li),wi.toRgba(Li,Oi,zi)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>D?v:j}return v}let x=a(c,h,p),b=Qr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function oa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Is.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,$=this._workCell;if(b.length>0&&G===b[0][0]&&A){let ke=b.shift(),Ue=this._isCellInSelection(ke[0],t);for(N=ke[0]+1;N=ke[1]),A?(U=!0,$=new c2(this._workCell,e.translateToString(!0,ke[0],ke[1]),ke[1]-ke[0]),z=ke[1]-1,Y=$.getWidth()):B=ke[1]}let ge=this._isCellInSelection(G,t),T=i&&G===o,M=F&&G>=f&&G<=_,V=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,ke=>{V=!0});let C=$.getChars()||Is;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),be=Y*h-p.get(C,$.isBold(),$.isItalic()),!j)j=this._document.createElement("span");else if(D&&(ge&&fe||!ge&&!fe&&$.bg===I)&&(ge&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===q&&M===R&&be===ie&&!T&&!U&&!V&&A){$.isInvisible()?E+=Is:E+=C,D++;continue}else D&&(j.textContent=E),j=this._document.createElement("span"),D=0,E="";if(I=$.bg,te=$.fg,q=$.extended.ext,R=M,ie=be,fe=ge,U&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ne.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ne.push("xterm-cursor-blink"),ne.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ne.push("xterm-cursor-outline");break;case"block":ne.push("xterm-cursor-block");break;case"bar":ne.push("xterm-cursor-bar");break;case"underline":ne.push("xterm-cursor-underline");break}}if($.isBold()&&ne.push("xterm-bold"),$.isItalic()&&ne.push("xterm-italic"),$.isDim()&&ne.push("xterm-dim"),$.isInvisible()?E=Is:E=$.getChars()||Is,$.isUnderline()&&(ne.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())j.style.textDecorationColor=`rgb(${Ho.toColorRGB($.getUnderlineColor()).join(",")})`;else{let ke=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&ke<8&&(ke+=8),j.style.textDecorationColor=v.ansi[ke].css}$.isOverline()&&(ne.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ne.push("xterm-strikethrough"),M&&(j.style.textDecoration="underline");let X=$.getFgColor(),se=$.getFgColorMode(),le=$.getBgColor(),K=$.getBgColorMode(),he=!!$.isInverse();if(he){let ke=X;X=le,le=ke;let Ue=se;se=K,K=Ue}let _e,Me,Le=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,ke=>{ke.options.layer!=="top"&&Le||(ke.backgroundColorRGB&&(K=50331648,le=ke.backgroundColorRGB.rgba>>8&16777215,_e=ke.backgroundColorRGB),ke.foregroundColorRGB&&(se=50331648,X=ke.foregroundColorRGB.rgba>>8&16777215,Me=ke.foregroundColorRGB),Le=ke.options.layer==="top")}),!Le&&ge&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,le=_e.rgba>>8&16777215,K=50331648,Le=!0,v.selectionForeground&&(se=50331648,X=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Le&&ne.push("xterm-decoration-top");let He;switch(K){case 16777216:case 33554432:He=v.ansi[le],ne.push(`xterm-bg-${le}`);break;case 50331648:He=wi.toColor(le>>16,le>>8&255,le&255),this._addStyle(j,`background-color:#${Db((le>>>0).toString(16),"0",6)}`);break;case 0:default:he?(He=v.foreground,ne.push("xterm-bg-257")):He=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(He,.5)),se){case 16777216:case 33554432:$.isBold()&&X<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(X+=8),this._applyMinimumContrast(j,He,v.ansi[X],$,_e,void 0)||ne.push(`xterm-fg-${X}`);break;case 50331648:let ke=wi.toColor(X>>16&255,X>>8&255,X&255);this._applyMinimumContrast(j,He,ke,$,_e,Me)||this._addStyle(j,`color:#${Db(X.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(j,He,v.foreground,$,_e,Me)||he&&ne.push("xterm-fg-257")}ne.length&&(j.className=ne.join(" "),ne.length=0),!T&&!U&&!V&&A?D++:j.textContent=E,be!==this.defaultSpacing&&(j.style.letterSpacing=`${be}px`),x.push(j),G=z}return j&&D&&(j.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||d2(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=Qt.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]}};cp=ci([Re(1,$y),Re(2,gn),Re(3,ns),Re(4,ba),Re(5,Uo),Re(6,xl)],cp);function Db(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}},m2=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 g2(){return new m2}var lf="xterm-dom-renderer-owner-",tr="xterm-rows",su="xterm-fg-",Mb="xterm-bg-",uo="xterm-focus",au="xterm-selection",x2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=x2++,this._rowElements=[],this._selectionRenderModel=g2(),this.onRequestRedraw=this._register(new we).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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=f2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new p2(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: ${Qt.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}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .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} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Mb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Mb}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(uo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(uo),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,j=this._rowElements[v],D=h.lines.get(S);if(!j||!D)break;j.replaceChildren(...this._rowFactory.createRow(D,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=ci([Re(7,$p),Re(8,Hu),Re(9,gn),Re(10,mn),Re(11,ba),Re(12,ns),Re(13,xl)],up);var hp=class extends ht{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new we),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new b2(this._optionsService))}catch{this._measureStrategy=this._register(new _2(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())}};hp=ci([Re(2,gn)],hp);var l0=class extends ht{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)}},_2=class extends l0{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}},b2=class extends l0{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}},v2=class extends ht{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 y2(this._window)),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new we),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(en.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ze(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ze(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}},y2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new pl),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ze(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)}},S2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ii(()=>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 Xp(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 w2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Xp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return w2(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=Xp(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])}}};dp=ci([Re(0,rs),Re(1,Hu)],dp);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=[]}},o0={};BC(o0,{getSafariVersion:()=>E2,isChromeOS:()=>d0,isFirefox:()=>c0,isIpad:()=>N2,isIphone:()=>j2,isLegacyEdge:()=>k2,isLinux:()=>Zp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>u0,isWindows:()=>h0});var Uu=typeof process<"u"&&"title"in process,$o=Uu?"node":navigator.userAgent,Fo=Uu?"node":navigator.platform,c0=$o.includes("Firefox"),k2=$o.includes("Edge"),u0=/^((?!chrome|android).)*safari/i.test($o);function E2(){if(!u0)return 0;let e=$o.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Fo),N2=Fo==="iPad",j2=Fo==="iPhone",h0=["Windows","Win16","Win32","WinCE"].includes(Fo),Zp=Fo.indexOf("Linux")>=0,d0=/\bCrOS\b/.test($o),f0=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()}},T2=class extends f0{_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())}}},A2=class extends f0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?A2:T2,R2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{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 pl),this._pausedResizeTask=new R2,this._observerDisposable=this._register(new pl),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 we),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new we),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new we),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new C2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new D2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ii(()=>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()}};fp=ci([Re(2,gn),Re(3,Hu),Re(4,ba),Re(5,Uo),Re(6,mn),Re(7,ns),Re(8,xl)],fp);var D2=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 M2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return O2(a,o,e,t,i,s)+$u(o,t,i,s)+z2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Bo(Math.abs(a-e),Mo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=L2(o>t?e:a,i)+(h-1)*i.cols+1+B2(o>t?a:e);return Bo(p,Mo(c,s))}function B2(e,t){return e-1}function L2(e,t){return t.cols-e}function O2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Bo(m0(e,t,e,t-xa(t,a),!1,a).length,Mo("D",o))}function $u(e,t,i,s){let a=e-xa(e,i),o=t-xa(t,i),c=Math.abs(a-o)-P2(e,t,i);return Bo(c,Mo(p0(e,t),s))}function z2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-xa(s,a):c=t;let h=s,p=I2(e,t,i,s,a,o);return Bo(m0(e,c,i,h,p==="C",a).length,Mo(p,o))}function P2(e,t,i){var c;let s=0,a=e-xa(e,i),o=t-xa(t,i);for(let h=0;h=0&&e0?c=s-xa(s,a):c=t,e=i&&ct?"A":"B"}function m0(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 Mo(e,t){let i=t?"O":"[";return me.ESC+i+e}function Bo(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 Bb(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 of=50,U2=15,$2=50,F2=500,q2=" ",W2=new RegExp(q2,"g"),pp=class extends ht{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 we),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new we),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new H2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(W2," ")).join(h0?`\r +`))}},ok=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},ck=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},uk=0,tf=class{constructor(e){this.value=e,this.id=uk++}},hk=2,dk,we=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new ak((t==null?void 0:t.onListenerError)??fu,((s=this._options)==null?void 0:s.leakWarningThreshold)??sk):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new rk(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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||fu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new tf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof tf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof zs?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Zf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new we,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new we,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}};Zf.INSTANCE=new Zf;var Wp=Zf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Wp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Wp.INSTANCE.getZoomFactor(e)}Wp.INSTANCE.onDidChangeFullscreen;var hl=typeof navigator=="object"?navigator.userAgent:"",Qf=hl.indexOf("Firefox")>=0,gk=hl.indexOf("AppleWebKit")>=0,Gp=hl.indexOf("Chrome")>=0,xk=!Gp&&hl.indexOf("Safari")>=0;hl.indexOf("Electron/")>=0;hl.indexOf("Android")>=0;var nf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");nf=e.matches,pk(is,e,({matches:i})=>{nf&&t.matches||(nf=i)})}var il="en",Jf=!1,ep=!1,pu=!1,Jy=!1,Jc,mu=il,_b=il,_k,fr,ha=globalThis,Zi,Ty;typeof ha.vscode<"u"&&typeof ha.vscode.process<"u"?Zi=ha.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(Zi=process);var Ay,bk=typeof((Ay=Zi==null?void 0:Zi.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(Zi==null?void 0:Zi.type)==="renderer",Ry;if(typeof Zi=="object"){Jf=Zi.platform==="win32",ep=Zi.platform==="darwin",pu=Zi.platform==="linux",pu&&Zi.env.SNAP&&Zi.env.SNAP_REVISION,Zi.env.CI||Zi.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Jc=il,mu=il;let e=Zi.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Jc=t.userLocale,_b=t.osLocale,mu=t.resolvedLanguage||il,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(fr=navigator.userAgent,Jf=fr.indexOf("Windows")>=0,ep=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,pu=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,mu=globalThis._VSCODE_NLS_LANGUAGE||il,Jc=navigator.language.toLowerCase(),_b=Jc):console.error("Unable to resolve platform.");var e0=Jf,Tr=ep,yk=pu,bb=Jy,Ar=fr,As=mu,Sk;(e=>{function t(){return As}e.value=t;function i(){return As.length===2?As==="en":As.length>=3?As[0]==="e"&&As[1]==="n"&&As[2]==="-":!1}e.isDefaultVariant=i;function s(){return As==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ha.postMessage=="function"&&!ha.importScripts;(()=>{if(wk){let e=[];ha.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}),ha.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Ar&&Ar.indexOf("Chrome")>=0);Ar&&Ar.indexOf("Firefox")>=0;!Ck&&Ar&&Ar.indexOf("Safari")>=0;Ar&&Ar.indexOf("Edg/")>=0;Ar&&Ar.indexOf("Android")>=0;var Ka=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ka&&Ka.clipboard&&Ka.clipboard.writeText,bb||Ka&&Ka.clipboard&&Ka.clipboard.readText;var Yp=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}},rf=new Yp,vb=new Yp,yb=new Yp,kk=new Array(230),t0;(e=>{function t(h){return rf.keyCodeToStr(h)}e.toString=t;function i(h){return rf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 rf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Qi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new we),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Vp=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 Gf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Gf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Gf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=class rr{static fromArray(t){return new rr(i=>{i.emitMany(t)})}static fromPromise(t){return new rr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new rr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new rr(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 we,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 rr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return rr.map(this,t)}static filter(t,i){return new rr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return rr.filter(this,t)}static coalesce(t){return rr.filter(t,i=>!!i)}coalesce(){return rr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return rr.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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Nr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:is,disposables:new zs};e.set(is.vscodeWindowId,t);let i=new we,s=new we,a=new we;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 ht.None;let h=new zs,p={window:c,disposables:h.add(new zs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ze(c,Li.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Nr(c).document}}})(),Uk=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 Ze(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ze(e,t,i,s)},Kp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Nr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){fu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Nr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Li={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"},qk=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 Eo(e){return new qk(e)}var r0=class{constructor(){this._hooks=new zs,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(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Nr(e)}this._hooks.add(Ze(o,Li.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ze(o,Li.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 kr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(kr||(kr={}));var bo=class en extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Qi.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ze(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ze(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ze(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!en.isTouchDevice())return ht.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!en.isTouchDevice())return ht.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||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(kr.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],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(kr.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===kr.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===kr.Change||t.type===kr.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,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=en.SCROLL_FRICTION*x,h+=en.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(kr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};bo.SCROLL_FRICTION=-.005,bo.HOLD_DELAY=700,bo.CLEAR_TAP_COUNT_TIME=400,ui([Wk],bo,"isTouchDevice",1);var Gk=bo,Xp=class extends ht{onclick(e,t){this._register(Ze(e,Li.CLICK,i=>t(new eu(Nr(e),i))))}onmousedown(e,t){this._register(Ze(e,Li.MOUSE_DOWN,i=>t(new eu(Nr(e),i))))}onmouseover(e,t){this._register(Ze(e,Li.MOUSE_OVER,i=>t(new eu(Nr(e),i))))}onmouseleave(e,t){this._register(Ze(e,Li.MOUSE_LEAVE,i=>t(new eu(Nr(e),i))))}onkeydown(e,t){this._register(Ze(e,Li.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ze(e,Li.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ze(e,Li.INPUT,t))}onblur(e,t){this._register(Ze(e,Li.BLUR,t))}onfocus(e,t){this._register(Ze(e,Li.FOCUS,t))}onchange(e,t){this._register(Ze(e,Li.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Xp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Li.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Li.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Vp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Nr(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()}},Vk=class tp{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 tp(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 tp(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}}},Kk=class extends ht{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function sf(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Xp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=Eo(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(Ze(this.domNode.domNode,Li.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Eo(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(Ze(this.slider.domNode,Li.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=Fk(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(e0&&c>e2){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()}},a0=class np{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 np(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=np._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};rp.INSTANCE=new rp;var s2=rp,a2=class extends Xp{constructor(e,t,i){super(),this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new we),this.onWillScroll=this._onWillScroll.event,this._options=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=Eo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Eo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Eo(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 Vp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=da(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,Tr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=da(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ze(this._listenOnDomNode,Li.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Tr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Tr&&(t.className+=" mac"),t}var sp=class extends ht{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Qi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(Qi.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(f=>this._handleScroll(f)))}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}};sp=ui([Re(2,pn),Re(3,ns),Re(4,Hy),Re(5,ul),Re(6,mn),Re(7,rs)],sp);var ap=class extends ht{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(ii(()=>{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()}};ap=ui([Re(1,pn),Re(2,ns),Re(3,Io),Re(4,rs)],ap);var c2=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)}},wr={full:0,left:0,center:0,right:0},Rs={full:0,left:0,center:0,right:0},lo={full:0,left:0,center:0,right:0},ku=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{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);Rs.full=this._canvas.width,Rs.left=e,Rs.center=t,Rs.right=e,this._refreshDrawHeightConstants(),lo.full=1,lo.left=1,lo.center=1+Rs.left,lo.right=1+Rs.left+Rs.center}_refreshDrawHeightConstants(){wr.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);wr.left=t,wr.center=t,wr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.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(lo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-wr[e.position||"full"]/2),Rs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+wr[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}))}};ku=ui([Re(2,pn),Re(3,Io),Re(4,rs),Re(5,mn),Re(6,ul),Re(7,ns)],ku);var me;(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=""))(me||(me={}));var gu;(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="Ÿ"))(gu||(gu={}));var l0;(e=>e.ST=`${me.ESC}\\`)(l0||(l0={}));var lp=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)}}};lp=ui([Re(2,pn),Re(3,mn),Re(4,ma),Re(5,rs)],lp);var Oi=0,zi=0,Pi=0,oi=0,Db={css:"#00000000",rgba:0},Ci;(e=>{function t(a,o,c,h){return h!==void 0?`#${ra(a)}${ra(o)}${ra(c)}${ra(h)}`:`#${ra(a)}${ra(o)}${ra(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 Qt;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Oi=v+Math.round((_-v)*oi),zi=S+Math.round((x-S)*oi),Pi=N+Math.round((b-N)*oi);let M=Ci.toCss(Oi,zi,Pi),E=Ci.toRgba(Oi,zi,Pi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=xu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ci.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Oi,zi,Pi]=xu.toChannels(f),{css:Ci.toCss(Oi,zi,Pi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Oi,zi,Pi]=xu.toChannels(p.rgba),{css:Ci.toCss(Oi,zi,Pi,oi),rgba:Ci.toRgba(Oi,zi,Pi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var si;(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),Ci.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),oi=parseInt(a.slice(4,5).repeat(2),16),Ci.toColor(Oi,zi,Pi,oi);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]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ci.toColor(Oi,zi,Pi,oi);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,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ci.toRgba(Oi,zi,Pi,oi),css:a}}e.toColor=s})(si||(si={}));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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(un||(un={}));var xu;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Oi=x+Math.round((p-x)*oi),zi=b+Math.round((f-b)*oi),Pi=v+Math.round((_-v)*oi),Ci.toRgba(Oi,zi,Pi)}e.blend=t;function i(c,h,p){let f=un.relativeLuminance(c>>8),_=un.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=Qr(f,un.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,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 ra(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Os.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,$=this._workCell;if(b.length>0&&G===b[0][0]&&A){let Ce=b.shift(),Ue=this._isCellInSelection(Ce[0],t);for(j=Ce[0]+1;j=Ce[1]),A?(U=!0,$=new u2(this._workCell,e.translateToString(!0,Ce[0],Ce[1]),Ce[1]-Ce[0]),z=Ce[1]-1,Y=$.getWidth()):B=Ce[1]}let ge=this._isCellInSelection(G,t),T=i&&G===o,D=F&&G>=f&&G<=_,K=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,Ce=>{K=!0});let C=$.getChars()||Os;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),be=Y*h-p.get(C,$.isBold(),$.isItalic()),!N)N=this._document.createElement("span");else if(M&&(ge&&fe||!ge&&!fe&&$.bg===I)&&(ge&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===q&&D===R&&be===ie&&!T&&!U&&!K&&A){$.isInvisible()?E+=Os:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=$.bg,te=$.fg,q=$.extended.ext,R=D,ie=be,fe=ge,U&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ne.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ne.push("xterm-cursor-blink"),ne.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ne.push("xterm-cursor-outline");break;case"block":ne.push("xterm-cursor-block");break;case"bar":ne.push("xterm-cursor-bar");break;case"underline":ne.push("xterm-cursor-underline");break}}if($.isBold()&&ne.push("xterm-bold"),$.isItalic()&&ne.push("xterm-italic"),$.isDim()&&ne.push("xterm-dim"),$.isInvisible()?E=Os:E=$.getChars()||Os,$.isUnderline()&&(ne.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Po.toColorRGB($.getUnderlineColor()).join(",")})`;else{let Ce=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&Ce<8&&(Ce+=8),N.style.textDecorationColor=v.ansi[Ce].css}$.isOverline()&&(ne.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ne.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let X=$.getFgColor(),re=$.getFgColorMode(),le=$.getBgColor(),V=$.getBgColorMode(),he=!!$.isInverse();if(he){let Ce=X;X=le,le=Ce;let Ue=re;re=V,V=Ue}let _e,Me,Le=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,Ce=>{Ce.options.layer!=="top"&&Le||(Ce.backgroundColorRGB&&(V=50331648,le=Ce.backgroundColorRGB.rgba>>8&16777215,_e=Ce.backgroundColorRGB),Ce.foregroundColorRGB&&(re=50331648,X=Ce.foregroundColorRGB.rgba>>8&16777215,Me=Ce.foregroundColorRGB),Le=Ce.options.layer==="top")}),!Le&&ge&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,le=_e.rgba>>8&16777215,V=50331648,Le=!0,v.selectionForeground&&(re=50331648,X=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Le&&ne.push("xterm-decoration-top");let He;switch(V){case 16777216:case 33554432:He=v.ansi[le],ne.push(`xterm-bg-${le}`);break;case 50331648:He=Ci.toColor(le>>16,le>>8&255,le&255),this._addStyle(N,`background-color:#${Mb((le>>>0).toString(16),"0",6)}`);break;case 0:default:he?(He=v.foreground,ne.push("xterm-bg-257")):He=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(He,.5)),re){case 16777216:case 33554432:$.isBold()&&X<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(X+=8),this._applyMinimumContrast(N,He,v.ansi[X],$,_e,void 0)||ne.push(`xterm-fg-${X}`);break;case 50331648:let Ce=Ci.toColor(X>>16&255,X>>8&255,X&255);this._applyMinimumContrast(N,He,Ce,$,_e,Me)||this._addStyle(N,`color:#${Mb(X.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,He,v.foreground,$,_e,Me)||he&&ne.push("xterm-fg-257")}ne.length&&(N.className=ne.join(" "),ne.length=0),!T&&!U&&!K&&A?M++:N.textContent=E,be!==this.defaultSpacing&&(N.style.letterSpacing=`${be}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=Qt.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]}};op=ui([Re(1,Fy),Re(2,mn),Re(3,ns),Re(4,ma),Re(5,Io),Re(6,ul)],op);function Mb(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}},g2=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 x2(){return new g2}var af="xterm-dom-renderer-owner-",nr="xterm-rows",iu="xterm-fg-",Bb="xterm-bg-",oo="xterm-focus",nu="xterm-selection",_2=1,cp=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new we).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(nr),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(nu),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(op,document),this._element.classList.add(af+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(af+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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} .${nr} 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} .${nr} { 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} .${nr} .xterm-dim { color: ${Qt.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} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${nu} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${nu} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${nu} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${iu}${o} { color: ${c.css}; }${this._terminalSelector} .${iu}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${iu}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${iu}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(oo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(oo),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${af}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};cp=ui([Re(7,Fp),Re(8,zu),Re(9,mn),Re(10,pn),Re(11,ma),Re(12,ns),Re(13,ul)],cp);var up=class extends ht{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new we),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};up=ui([Re(2,mn)],up);var o0=class extends ht{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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=class extends ht{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 S2(this._window)),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new we),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Qi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ze(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ze(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}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ll),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ze(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)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ii(()=>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 Zp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Zp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var hp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Zp(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])}}};hp=ui([Re(0,rs),Re(1,zu)],hp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Qp,isMac:()=>Nu,isNode:()=>Pu,isSafari:()=>h0,isWindows:()=>d0});var Pu=typeof process<"u"&&"title"in process,Ho=Pu?"node":navigator.userAgent,Uo=Pu?"node":navigator.platform,u0=Ho.includes("Firefox"),E2=Ho.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Ho);function N2(){if(!h0)return 0;let e=Ho.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Nu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Uo),j2=Uo==="iPad",T2=Uo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(Uo),Qp=Uo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Ho),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},ju=!Pu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new ju}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},dp=class extends ht{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 ll),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new ll),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 we),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new we),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new we),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ii(()=>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()}};dp=ui([Re(2,mn),Re(3,zu),Re(4,ma),Re(5,Io),Re(6,pn),Re(7,ns),Re(8,ul)],dp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+Iu(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Do(Math.abs(a-e),Ro(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Do(p,Ro(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return Iu(t,s,a,o).length===0?"":Do(g0(e,t,e,t-fa(t,a),!1,a).length,Ro("D",o))}function Iu(e,t,i,s){let a=e-fa(e,i),o=t-fa(t,i),c=Math.abs(a-o)-I2(e,t,i);return Do(c,Ro(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;Iu(t,s,a,o).length>0?c=s-fa(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Do(g0(e,c,i,h,p==="C",a).length,Ro(p,o))}function I2(e,t,i){var c;let s=0,a=e-fa(e,i),o=t-fa(t,i);for(let h=0;h=0&&e0?c=s-fa(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Ro(e,t){let i=t?"O":"[";return me.ESC+i+e}function Do(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 Lb(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 lf=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),fp=class extends ht{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 lr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new we),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new we),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Zp&&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=Bb(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=Xp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*(U2-1)))}shouldForceSelection(e){return Au?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(),$2)}_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&&!(Au&&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,f=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+=N-1,p+=N-1);D>0&&h>0&&!this._isCharWordSeparator(o.loadCell(D-1,this._workCell));){o.loadCell(D-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,D--):I>1&&(b+=I-1,h-=I-1),h--,D--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,j=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let D=a.lines.get(e[1]-1);if(D&&o.isWrapped&&D.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let N=this._bufferService.cols-E.start;S-=N,j+=N}}}if(s&&S+j===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let D=a.lines.get(e[1]+1);if(D!=null&&D.isWrapped&&D.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(j+=E.length)}}return{start:S,length:j}}}_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=Bb(i,this._bufferService.cols)}};pp=ci([Re(3,mn),Re(4,ba),Re(5,Fp),Re(6,gn),Re(7,rs),Re(8,ns)],pp);var Lb=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={}}},Ob=class{constructor(){this._color=new Lb,this._css=new Lb}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=[ri.toColor("#2e3436"),ri.toColor("#cc0000"),ri.toColor("#4e9a06"),ri.toColor("#c4a000"),ri.toColor("#3465a4"),ri.toColor("#75507b"),ri.toColor("#06989a"),ri.toColor("#d3d7cf"),ri.toColor("#555753"),ri.toColor("#ef2929"),ri.toColor("#8ae234"),ri.toColor("#fce94f"),ri.toColor("#729fcf"),ri.toColor("#ad7fa8"),ri.toColor("#34e2e2"),ri.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})()),da=ri.toColor("#ffffff"),So=ri.toColor("#000000"),zb=ri.toColor("#ffffff"),Pb=So,ho={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},G2=da,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new Ob,this._halfContrastCache=new Ob,this._onChangeColors=this._register(new we),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:So,cursor:zb,cursorAccent:Pb,selectionForeground:void 0,selectionBackgroundTransparent:ho,selectionBackgroundOpaque:Qt.blend(So,ho),selectionInactiveBackgroundTransparent:ho,selectionInactiveBackgroundOpaque:Qt.blend(So,ho),scrollbarSliderBackground:Qt.opacity(da,.2),scrollbarSliderHoverBackground:Qt.opacity(da,.4),scrollbarSliderActiveBackground:Qt.opacity(da,.5),overviewRulerBorder:da,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=$t(e.foreground,da),t.background=$t(e.background,So),t.cursor=Qt.blend(t.background,$t(e.cursor,zb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Pb)),t.selectionBackgroundTransparent=$t(e.selectionBackground,ho),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Rb):void 0,t.selectionForeground===Rb&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,G2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(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)}},V2={trace:0,debug:1,info:2,warn:3,error:4,off:5},X2="xterm.js: ",gp=class extends ht{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=V2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?zs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=zs(i):a&2097151?(this._combined[t]=zs(a&2097151)+zs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Z2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(D>x||_[D].getTrimmedLength()===0);D--)j++;j>0&&(c.push(h+_.length-j),c.push(j)),h+=_.length-1}return c}function Q2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cLo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Lo(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 x0=class _0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=_0._nextId++,this._onDispose=this.register(new we),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ga(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};x0._nextId=1;var tE=x0,Di={},fa=Di.B;Di[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Hb=4294967295,Ub=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=fa,this.markers=[],this._nullCell=sr.fromCharData([0,Ly,1,0]),this._whitespaceCell=sr.fromCharData([0,Is,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ib(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new wo(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&&eHb?Hb: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 Ib(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 wo(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=Z2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Si),i);if(s.length>0){let a=Q2(this.lines,s);J2(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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,j=_[S];j===0&&(S--,j=_[S]);let D=p.length-x-1,E=f;for(;D>=0;){let I=Math.min(E,j);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[D],E-I,j-I,I,!0),j-=I,j===0&&(S--,j=_[S]),E-=I,E===0){D--;let te=Math.max(D,0);E=Lo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let j=0;j=0;j--)if(x&&x.start>f+b){for(let D=x.newLines.length-1;D>=0;D--)this.lines.set(j--,x.newLines[D]);j++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(j,h[f--]);let v=0;for(let j=c.length-1;j>=0;j--)c[j].index+=v,this.lines.onInsertEmitter.fire(c[j]),v+=c[j].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},iE=class extends ht{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new we),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 Ub(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ub(!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)}},b0=2,v0=1,xp=class extends ht{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,b0),this.rows=Math.max(e.rawOptions.rows||0,v0),this.buffers=this._register(new iE(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))}};xp=ci([Re(0,gn)],xp);var nl={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},nE=["normal","bold","100","200","300","400","500","600","700","800","900"],rE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new we),this.onOptionChange=this._onOptionChange.event;let t={...nl};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(ii(()=>{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 nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in nl))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=nl[e]),!sE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=nE.includes(t)?t:nl[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 sE(e){return e==="block"||e==="underline"||e==="bar"}function Co(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]&&Co(e[s],t-1);return i}var $b=Object.freeze({insertMode:!1}),Fb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{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 we),this.onData=this._onData.event,this._onUserInput=this._register(new we),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new we),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Co($b),this.decPrivateModes=Co(Fb)}reset(){this.modes=Co($b),this.decPrivateModes=Co(Fb)}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))}};_p=ci([Re(0,mn),Re(1,Hy),Re(2,gn)],_p);var qb={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 uf(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 hf=String.fromCharCode,Wb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{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 we),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(qb))this.addProtocol(s,qb[s]);for(let s of Object.keys(Wb))this.addEncoding(s,Wb[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)}};bp=ci([Re(0,mn),Re(1,ba),Re(2,gn)],bp);var df=[[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]],aE=[[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]],Ai;function lE(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=pa.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return pa.createPropertyValue(0,i,s)}},pa=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new we,this.onChange=this._onChange.event;let t=new oE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},cE=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 Gb(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 fo=2147483647,uE=256,y0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>uE)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 vp;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>fo?fo: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>fo?fo: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,fo):t}},po=[],hE=class{constructor(){this._state=0,this._active=po,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=po}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=po,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||po,!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",Iu(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=po,this._id=-1,this._state=0}}},Pn=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+=Iu(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}},mo=[],dE=class{constructor(){this._handlers=Object.create(null),this._active=mo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=mo}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=mo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||mo,!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",Iu(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=mo,this._ident=0}},ko=new y0;ko.addParam(0);var Yb=class{constructor(e){this._handler=e,this._data="",this._params=ko,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ko,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=ko,this._data="",this._hitLimit=!1,i));return this._params=ko,this._data="",this._hitLimit=!1,t}},fE=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})(),mE=class extends ht{constructor(e=pE){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 y0,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(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new hE),this._dcsParser=this._register(new dE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 _E(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var bE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ls=131072,Vb=10;function Xb(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 Zb=5e3,Qb=0,vE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new mE){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 IC,this._utf8Decoder=new HC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone(),this._onRequestBell=this._register(new we),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new we),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new we),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new we),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new we),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new we),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new we),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new we),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new we),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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Pn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Pn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Pn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Pn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Pn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Pn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Pn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Pn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Pn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Pn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Pn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Pn(f=>this.restoreCursorColor(f))),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 f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Yb((f,_)=>this.requestStatusString(f,_)))}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"),Zb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Zb} 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>Ls&&(o=this._parseStack.position+Ls)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthLs)for(let f=o;f0&&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,N=this._activeBuffer.x-D;for(this._activeBuffer.x=D,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),D>0&&x instanceof wo&&x.copyCellsFrom(E,N,0,D,!1);N=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-D,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=>Xb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Yb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Pn(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 f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(j[j.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",j[j.SET=1]="SET",j[j.RESET=2]="RESET",j[j.PERMANENTLY_SET=3]="PERMANENTLY_SET",j[j.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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(j,D)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${j};${D}$y`),!0),v=j=>j?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ho.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(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.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(`${me.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(!Xb(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(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Vb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Vb&&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(Jb(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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 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(`${me.ESC}${c}${me.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)}},yp=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&&(Qb=e,e=t,t=Qb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=ci([Re(0,mn)],yp);function Jb(e){return 0<=e&&e<256}var yE=5e7,ev=12,SE=50,wE=class extends ht{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 we),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>yE)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>=ev?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>=ev)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>SE&&(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()}},Sp=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)))}};Sp=ci([Re(0,mn)],Sp);var tv=!1,CE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new pl),this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onData=this._register(new we),this.onData=this._onData.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new we),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new we),this._instantiationService=new K2,this.optionsService=this._register(new rE(e)),this._instantiationService.setService(gn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(mn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Hy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(ba,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Iy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pa)),this._instantiationService.setService(qC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(cE),this._instantiationService.setService(FC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService(Uy,this._oscLinkService),this._inputHandler=this._register(new vE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(en.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(en.forward(this._bufferService.onResize,this._onResize)),this._register(en.forward(this.coreService.onData,this._onData)),this._register(en.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 wE((t,i)=>this._inputHandler.parse(t,i))),this._register(en.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new we),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&&!tv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),tv=!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,b0),t=Math.max(t,v0),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(Gb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Gb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},kE={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 EE(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=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.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=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=kE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.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=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var pi=0,NE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(pi=this._search(t),pi===-1)||this._getKey(this._array[pi])!==t)return!1;do if(this._array[pi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pi),!0;while(++pia-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&&(pi=this._search(e),!(pi<0||pi>=this._array.length)&&this._getKey(this._array[pi])===e))do yield this._array[pi];while(++pi=this._array.length)&&this._getKey(this._array[pi])===e))do t(this._array[pi]);while(++pi=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}},pf=0,iv=0,jE=class extends ht{constructor(){super(),this._decorations=new NE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new we),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new we),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new TE(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{pf=a.options.x??0,iv=pf+(a.options.width??1),e>=pf&&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)}},nv=20,Du=class extends ht{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 RE(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(Ze(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{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===nv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;ga(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(Ze(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ze(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ze(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ze(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&DE(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,ga(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}}};wp=ci([Re(1,Fp),Re(2,rs),Re(3,mn),Re(4,Fy)],wp);function DE(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 ME=class extends CE{constructor(e={}){super(e),this._linkifier=this._register(new pl),this.browser=o0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new pl),this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new we),this.onKey=this._onKey.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new we),this.onBell=this._onBell.event,this._onFocus=this._register(new we),this._onBlur=this._register(new we),this._onA11yCharEmitter=this._register(new we),this._onA11yTabEmitter=this._register(new we),this._onWillOpen=this._register(new we),this._setup(),this._decorationService=this._instantiationService.createInstance(jE),this._instantiationService.setService(Uo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(S2),this._instantiationService.setService(Fy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(en.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(en.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(en.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(en.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{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=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${_E(a)}${a0.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(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.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(me.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(Ze(this.element,"copy",t=>{this.hasSelection()&&zC(t,this._selectionService)}));let e=t=>PC(t,this.textarea,this.coreService,this.optionsService);this._register(Ze(this.textarea,"paste",e)),this._register(Ze(this.element,"paste",e)),c0?this._register(Ze(this.element,"mousedown",t=>{t.button===2&&fb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ze(this.element,"contextmenu",t=>{fb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Zp&&this._register(Ze(this.element,"auxclick",t=>{t.button===1&&By(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ze(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ze(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ze(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ze(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ze(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ze(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ze(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(Ze(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",Uf.get()),d0||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(v2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Ze(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ze(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(xl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService($y,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(rs,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Fp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(GC,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(en.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ze(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ze(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(Ze(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.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){My(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=EE(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===me.ETX||i.key===me.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 sr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},rv=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 OE(t)}getNullCell(){return new sr}},zE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new we),this.onBufferChange=this._onBufferChange.event,this._normal=new rv(this._core.buffers.normal,"normal"),this._alternate=new rv(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)}},PE=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)}},IE=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}},HE=["cols","rows"],Er=0,UE=class extends ht{constructor(e){super(),this._core=this._register(new ME(e)),this._addonManager=this._register(new LE),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(HE.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 PE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new IE(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 zE(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 Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<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())),Qp&&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=Lb(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=Zp(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,-lf),lf),t/=lf,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Nu?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(),F2)}_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&&!(Nu&&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,f=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+=j-1,p+=j-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let j=this._bufferService.cols-E.start;S-=j,N+=j}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};fp=ui([Re(3,pn),Re(4,ma),Re(5,qp),Re(6,mn),Re(7,rs),Re(8,ns)],fp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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=[si.toColor("#2e3436"),si.toColor("#cc0000"),si.toColor("#4e9a06"),si.toColor("#c4a000"),si.toColor("#3465a4"),si.toColor("#75507b"),si.toColor("#06989a"),si.toColor("#d3d7cf"),si.toColor("#555753"),si.toColor("#ef2929"),si.toColor("#8ae234"),si.toColor("#fce94f"),si.toColor("#729fcf"),si.toColor("#ad7fa8"),si.toColor("#34e2e2"),si.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})()),oa=si.toColor("#ffffff"),vo=si.toColor("#000000"),Pb=si.toColor("#ffffff"),Ib=vo,co={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=oa,pp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new we),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:oa,background:vo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:co,selectionBackgroundOpaque:Qt.blend(vo,co),selectionInactiveBackgroundTransparent:co,selectionInactiveBackgroundOpaque:Qt.blend(vo,co),scrollbarSliderBackground:Qt.opacity(oa,.2),scrollbarSliderHoverBackground:Qt.opacity(oa,.4),scrollbarSliderActiveBackground:Qt.opacity(oa,.5),overviewRulerBorder:oa,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=$t(e.foreground,oa),t.background=$t(e.background,vo),t.cursor=Qt.blend(t.background,$t(e.cursor,Pb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=$t(e.selectionBackground,co),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,Y2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",mp=class extends ht{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=X2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Bs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return ru=t*ut,i.content=this._data[ru+0],i.fg=this._data[ru+1],i.bg=this._data[ru+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Bs(i):a&2097151?(this._combined[t]=Bs(a&2097151)+Bs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*of=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cMo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Mo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new we),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),da(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Di={},ca=Di.B;Di[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=ca,this.markers=[],this._nullCell=lr.fromCharData([0,Oy,1,0]),this._whitespaceCell=lr.fromCharData([0,Os,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new ju,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Cu),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 Cu),this._whitespaceCell}getBlankLine(e,t){return new yo(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&&eUb?Ub: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 Hb(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 yo(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(wi),i);if(s.length>0){let a=J2(this.lines,s);eE(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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let te=Math.max(M,0);E=Mo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends ht{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new we),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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,gp=class extends ht{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};gp=ui([Re(0,mn)],gp);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:Nu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new we),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(ii(()=>{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]),!aE(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=rE.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 aE(e){return e==="block"||e==="underline"||e==="bar"}function So(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]&&So(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),xp=class extends ht{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 we),this.onData=this._onData.event,this._onUserInput=this._register(new we),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new we),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=So(Fb),this.decPrivateModes=So(qb)}reset(){this.modes=So(Fb),this.decPrivateModes=So(qb)}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))}};xp=ui([Re(0,pn),Re(1,Uy),Re(2,mn)],xp);var Wb={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 cf(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 uf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[cf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${uf(t[0])}${uf(t[1])}${uf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.x};${e.y}${t}`}},_p=class extends ht{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 we),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};_p=ui([Re(0,pn),Re(1,ma),Re(2,mn)],_p);var hf=[[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]],lE=[[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]],Ai;function oE(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=ua.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ua.createPropertyValue(0,i,s)}},ua=class _u{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new we,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=_u.extractWidth(h);_u.extractShouldJoin(h)&&(p-=_u.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 uo=2147483647,hE=256,S0=class bp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 bp;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>uo?uo: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>uo?uo: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,uo):t}},ho=[],dE=class{constructor(){this._state=0,this._active=ho,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=ho}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=ho,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ho,!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",Ou(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=ho,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+=Ou(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}},fo=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=fo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fo}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=fo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||fo,!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",Ou(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=fo,this._ident=0}},wo=new S0;wo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=wo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():wo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Ou(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=wo,this._data="",this._hitLimit=!1,i));return this._params=wo,this._data="",this._hitLimit=!1,t}},pE=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(sr,0,2,0),e.add(sr,8,5,8),e.add(sr,6,0,6),e.add(sr,11,0,11),e.add(sr,13,13,13),e})(),gE=class extends ht{constructor(e=mE){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 S0,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(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 df(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${df(i,t)}/${df(s,t)}/${df(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ds=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone(),this._onRequestBell=this._register(new we),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new we),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new we),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new we),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new we),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new we),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new we),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new we),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new we),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 vp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(gu.IND,()=>this.index()),this._parser.setExecuteHandler(gu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(gu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Hn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Hn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Hn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Hn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Hn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Hn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Hn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Hn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Hn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Hn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Hn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Hn(f=>this.restoreCursorColor(f))),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 f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>Ds&&(o=this._parseStack.position+Ds)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthDs)for(let f=o;f0&&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,j=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof yo&&x.copyCellsFrom(E,j,0,M,!1);j=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(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 f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Po.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(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.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(`${me.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(!Zb(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(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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 lr;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(`${me.ESC}${c}${me.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)}},vp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vp=ui([Re(0,pn)],vp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{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 we),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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},yp=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)))}};yp=ui([Re(0,pn)],yp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ll),this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onData=this._register(new we),this.onData=this._onData.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new we),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new we),this._instantiationService=new K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(mn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(pn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(ma,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ua)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(yp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Qi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Qi.forward(this._bufferService.onResize,this._onResize)),this._register(Qi.forward(this.coreService.onData,this._onData)),this._register(Qi.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(Qi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new we),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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.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=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=EE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.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=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var gi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new ju,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new ju,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||(gi=this._search(t),gi===-1)||this._getKey(this._array[gi])!==t)return!1;do if(this._array[gi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(gi),!0;while(++gia-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&&(gi=this._search(e),!(gi<0||gi>=this._array.length)&&this._getKey(this._array[gi])===e))do yield this._array[gi];while(++gi=this._array.length)&&this._getKey(this._array[gi])===e))do t(this._array[gi]);while(++gi=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}},ff=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new we),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new we),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{ff=a.options.x??0,nv=ff+(a.options.width??1),e>=ff&&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)}},rv=20,Tu=class extends ht{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 DE(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(Ze(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{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===rv+1&&(this._liveRegion.textContent+=Uf.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;da(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(Ze(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ze(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ze(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ze(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,da(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}}};Sp=ui([Re(1,qp),Re(2,rs),Re(3,pn),Re(4,qy)],Sp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new ll),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ll),this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new we),this.onKey=this._onKey.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new we),this.onBell=this._onBell.event,this._onFocus=this._register(new we),this._onBlur=this._register(new we),this._onA11yCharEmitter=this._register(new we),this._onA11yTabEmitter=this._register(new we),this._onWillOpen=this._register(new we),this._setup(),this._decorationService=this._instantiationService.createInstance(TE),this._instantiationService.setService(Io,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ff)),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(Qi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Qi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Qi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Qi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{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=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${bE(a)}${l0.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(me.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(me.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(Ze(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ze(this.textarea,"paste",e)),this._register(Ze(this.element,"paste",e)),u0?this._register(Ze(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ze(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Qp&&this._register(Ze(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ze(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ze(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ze(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ze(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ze(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ze(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ze(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(Ze(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",Hf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Ze(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ze(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(up,this._document,this._helperContainer),this._instantiationService.setService(zu,this._charSizeService),this._themeService=this._instantiationService.createInstance(pp),this._instantiationService.setService(ul,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Eu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(dp,this.rows,this.screenElement)),this._instantiationService.setService(rs,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(lp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hp),this._instantiationService.setService(qp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(Sp,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(sp,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(fp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(Qi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(ap,this.screenElement)),this._register(Ze(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(ku,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ku,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(cp,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ze(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(Ze(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.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){By(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=NE(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===me.ETX||i.key===me.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)&&(LE(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 lr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=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 zE(t)}getNullCell(){return new lr}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new we),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Cr=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 Hf.get()},set promptLabel(e){Hf.set(e)},get tooMuchOutput(){return Uf.get()},set tooMuchOutput(e){Uf.set(e)}}}_verifyIntegers(...e){for(Cr of e)if(Cr===1/0||isNaN(Cr)||Cr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Cr of e)if(Cr&&(Cr===1/0||isNaN(Cr)||Cr%1!==0||Cr<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 $E=2,FE=1,qE=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,f=s-h,_=a-p-t;return{cols:Math.max($E,Math.floor(_/e.css.cell.width)),rows:Math.max(FE,Math.floor(f/e.css.cell.height))}}};/** + */var FE=2,qE=1,WE=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,f=s-h,_=a-p-t;return{cols:Math.max(FE,Math.floor(_/e.css.cell.width)),rows:Math.max(qE,Math.floor(f/e.css.cell.height))}}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -94,48 +94,48 @@ 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 Pi=0,Ii=0,Hi=0,oi=0,rn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(rn||(rn={}));var WE;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Pi=v+Math.round((_-v)*oi),Ii=S+Math.round((x-S)*oi),Hi=j+Math.round((b-j)*oi);let D=rn.toCss(Pi,Ii,Hi),E=rn.toRgba(Pi,Ii,Hi);return{css:D,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return rn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Pi,Ii,Hi]=Su.toChannels(f),{css:rn.toCss(Pi,Ii,Hi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Pi,Ii,Hi]=Su.toChannels(p.rgba),{css:rn.toCss(Pi,Ii,Hi,oi),rgba:rn.toRgba(Pi,Ii,Hi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(WE||(WE={}));var Qi;(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 Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),rn.toColor(Pi,Ii,Hi);case 5:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),oi=parseInt(a.slice(4,5).repeat(2),16),rn.toColor(Pi,Ii,Hi,oi);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 Pi=parseInt(o[1]),Ii=parseInt(o[2]),Hi=parseInt(o[3]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),rn.toColor(Pi,Ii,Hi,oi);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),[Pi,Ii,Hi,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rn.toRgba(Pi,Ii,Hi,oi),css:a}}e.toColor=s})(Qi||(Qi={}));var dn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(dn||(dn={}));var Su;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Pi=x+Math.round((p-x)*oi),Ii=b+Math.round((f-b)*oi),Hi=v+Math.round((_-v)*oi),rn.toRgba(Pi,Ii,Hi)}e.blend=t;function i(c,h,p){let f=dn.relativeLuminance(c>>8),_=dn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>D?v:j}return v}let x=a(c,h,p),b=Jr(f,dn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Qi.toColor("#2e3436"),Qi.toColor("#cc0000"),Qi.toColor("#4e9a06"),Qi.toColor("#c4a000"),Qi.toColor("#3465a4"),Qi.toColor("#75507b"),Qi.toColor("#06989a"),Qi.toColor("#d3d7cf"),Qi.toColor("#555753"),Qi.toColor("#ef2929"),Qi.toColor("#8ae234"),Qi.toColor("#fce94f"),Qi.toColor("#729fcf"),Qi.toColor("#ad7fa8"),Qi.toColor("#34e2e2"),Qi.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:rn.toCss(s,a,o),rgba:rn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:rn.toCss(s,s,s),rgba:rn.toRgba(s,s,s)})}return e})());function sv(e,t,i){return Math.max(t,Math.min(e,i))}function YE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var S0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(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=!w0(e,t),a=!es(e,t),o=!C0(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?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(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&&(es(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},VE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:sv(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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 XE(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,f=t.scrollback,_=f===void 0?p:sv(f+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(){}},XE=class extends S0{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=GE}_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=!w0(e,t),a=!es(e,t),o=!C0(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+=YE(e.getChars())}_serializeString(){return this._htmlContent}};const ZE="__OWS_FRESH_SESSION__",rl="[REDACTED]",QE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${rl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${rl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${rl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${rl}`]];function av(e){let t=e;for(const[i,s]of QE)t=t.replace(i,s);return t}const lv="codex features enable image_generation";function JE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const eN={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"},tN="plotlink-terminal",iN=1,Us="scrollback",ov=10*1024*1024;function Qp(){return new Promise((e,t)=>{const i=indexedDB.open(tN,iN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Us)||s.createObjectStore(Us)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function sl(e,t){const i=t.length>ov?t.slice(-ov):t,s=await Qp();return new Promise((a,o)=>{const c=s.transaction(Us,"readwrite");c.objectStore(Us).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function nN(e){const t=await Qp();return new Promise((i,s)=>{const o=t.transaction(Us,"readonly").objectStore(Us).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await Qp();return new Promise((i,s)=>{const a=t.transaction(Us,"readwrite");a.objectStore(Us).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function rN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),j=w.useRef(i),[D,E]=w.useState([]),[N,I]=w.useState(new Set),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(!1),[B,ne]=w.useState(!1),F=JE(x,_),G=!!b,Y=w.useRef(()=>{});w.useEffect(()=>{j.current=i},[i]);const U=w.useCallback(K=>{var _e;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((_e=K.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),A=w.useCallback(K=>{for(const[he,_e]of Ri)_e.container.style.display=he===K?"block":"none";if(K){const he=Ri.get(K);he&&setTimeout(()=>U(he),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const ge=w.useCallback((K,he,_e)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Le=z.current[K]?"&bypass=true":"",He=$.current[K],ke=He?`&provider=${encodeURIComponent(He)}`:"",Ue=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${_e}${Le}${ke}`);Ue.onopen=()=>{he.connected=!0,he._retried=!1,I(at=>{const Ve=new Set(at);return Ve.delete(K),Ve}),Ue.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let Je=!0;Ue.onmessage=at=>{if(Je&&(Je=!1,typeof at.data=="string"&&at.data===ZE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof at.data=="string"?av(at.data):at.data)},Ue.onclose=at=>{if(he.connected=!1,he.ws===Ue){he.ws=null;try{const Ve=he.serialize.serialize();sl(K,Ve).catch(()=>{})}catch{}if(at.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r + */var Ii=0,Hi=0,Ui=0,ci=0,tn;(e=>{function t(a,o,c,h){return h!==void 0?`#${sa(a)}${sa(o)}${sa(c)}${sa(h)}`:`#${sa(a)}${sa(o)}${sa(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 GE;(e=>{function t(p,f){if(ci=(f.rgba&255)/255,ci===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Ii=v+Math.round((_-v)*ci),Hi=S+Math.round((x-S)*ci),Ui=N+Math.round((b-N)*ci);let M=tn.toCss(Ii,Hi,Ui),E=tn.toRgba(Ii,Hi,Ui);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=bu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return tn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Ii,Hi,Ui]=bu.toChannels(f),{css:tn.toCss(Ii,Hi,Ui),rgba:f}}e.opaque=a;function o(p,f){return ci=Math.round(f*255),[Ii,Hi,Ui]=bu.toChannels(p.rgba),{css:tn.toCss(Ii,Hi,Ui,ci),rgba:tn.toRgba(Ii,Hi,Ui,ci)}}e.opacity=o;function c(p,f){return ci=p.rgba&255,o(p,ci*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var Xi;(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 Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),tn.toColor(Ii,Hi,Ui);case 5:return Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),ci=parseInt(a.slice(4,5).repeat(2),16),tn.toColor(Ii,Hi,Ui,ci);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 Ii=parseInt(o[1]),Hi=parseInt(o[2]),Ui=parseInt(o[3]),ci=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),tn.toColor(Ii,Hi,Ui,ci);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),[Ii,Hi,Ui,ci]=t.getImageData(0,0,1,1).data,ci!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:tn.toRgba(Ii,Hi,Ui,ci),css:a}}e.toColor=s})(Xi||(Xi={}));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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var bu;(e=>{function t(c,h){if(ci=(h&255)/255,ci===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Ii=x+Math.round((p-x)*ci),Hi=b+Math.round((f-b)*ci),Ui=v+Math.round((_-v)*ci),tn.toRgba(Ii,Hi,Ui)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=Jr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,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})(bu||(bu={}));function sa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Xi.toColor("#2e3436"),Xi.toColor("#cc0000"),Xi.toColor("#4e9a06"),Xi.toColor("#c4a000"),Xi.toColor("#3465a4"),Xi.toColor("#75507b"),Xi.toColor("#06989a"),Xi.toColor("#d3d7cf"),Xi.toColor("#555753"),Xi.toColor("#ef2929"),Xi.toColor("#8ae234"),Xi.toColor("#fce94f"),Xi.toColor("#729fcf"),Xi.toColor("#ad7fa8"),Xi.toColor("#34e2e2"),Xi.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 av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(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=!C0(e,t),a=!es(e,t),o=!k0(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?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(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&&(es(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!es(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",Za="[REDACTED]",JE=[[/(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 lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,Ps="scrollback",cv=10*1024*1024;function Jp(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ps)||s.createObjectStore(Ps)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Qa(e,t){const i=t.length>cv?t.slice(-cv):t,s=await Jp();return new Promise((a,o)=>{const c=s.transaction(Ps,"readwrite");c.objectStore(Ps).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await Jp();return new Promise((i,s)=>{const o=t.transaction(Ps,"readonly").objectStore(Ps).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function pf(e){const t=await Jp();return new Promise((i,s)=>{const a=t.transaction(Ps,"readwrite");a.objectStore(Ps).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[j,I]=w.useState(new Set),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(!1),[B,ne]=w.useState(!1),F=eN(x,_),G=!!b,Y=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const U=w.useCallback(V=>{var _e;const{width:he}=V.container.getBoundingClientRect();if(!(he<50))try{V.fit.fit(),((_e=V.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&V.ws.send(JSON.stringify({type:"resize",cols:V.term.cols,rows:V.term.rows}))}catch{}},[]),A=w.useCallback(V=>{for(const[he,_e]of Ri)_e.container.style.display=he===V?"block":"none";if(V){const he=Ri.get(V);he&&setTimeout(()=>U(he),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const ge=w.useCallback((V,he,_e)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Le=z.current[V]?"&bypass=true":"",He=$.current[V],Ce=He?`&provider=${encodeURIComponent(He)}`:"",Ue=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(V)}&token=${e}&resume=${_e}${Le}${Ce}`);Ue.onopen=()=>{he.connected=!0,he._retried=!1,I(at=>{const Ke=new Set(at);return Ke.delete(V),Ke}),Ue.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let et=!0;Ue.onmessage=at=>{if(et&&(et=!1,typeof at.data=="string"&&at.data===QE)){he.term.reset(),pf(V).catch(()=>{});return}he.term.write(typeof at.data=="string"?lv(at.data):at.data)},Ue.onclose=at=>{if(he.connected=!1,he.ws===Ue){he.ws=null;try{const Ke=he.serialize.serialize();Qa(V,Ke).catch(()=>{})}catch{}if(at.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),Y.current(K,he,!1);return}I(Ve=>new Set(Ve).add(K))}},he.term.onData(at=>{Ue.readyState===WebSocket.OPEN&&Ue.send(at)}),he.ws=Ue},[e]);w.useEffect(()=>{Y.current=ge},[ge]);const T=w.useCallback(async(K,he)=>{if(!S.current||Ri.has(K))return;const{resume:_e=!1,autoConnect:Me=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const He=new UE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:eN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),ke=new qE,Ue=new VE;He.loadAddon(ke),He.loadAddon(Ue),He.open(Le);const Je={term:He,fit:ke,serialize:Ue,ws:null,container:Le,observer:null,connected:!1},at=new ResizeObserver(()=>{var Et;const{width:Ve}=Le.getBoundingClientRect();if(!(Ve<50))try{ke.fit(),((Et=Je.ws)==null?void 0:Et.readyState)===WebSocket.OPEN&&Je.ws.send(JSON.stringify({type:"resize",cols:He.cols,rows:He.rows}))}catch{}});at.observe(Le),Je.observer=at,Ri.set(K,Je),E(Ve=>[...Ve,K]);try{const Ve=await nN(K);if(Ve){const Et=av(Ve);He.write(Et),Et!==Ve&&sl(K,Et).catch(()=>{})}}catch{}Me?ge(K,Je,_e):I(Ve=>new Set(Ve).add(K)),setTimeout(()=>U(Je),50)},[ge,U]),M=w.useCallback(async(K,he)=>{const _e=Ri.get(K);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await j.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),ge(K,_e,he))},[ge]),V=w.useCallback(K=>{const he=Ri.get(K);if(he){try{const _e=he.serialize.serialize();sl(K,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(K),E(_e=>_e.filter(Me=>Me!==K)),I(_e=>{const Me=new Set(_e);return Me.delete(K),Me}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var _e;const he=Ri.get(K);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit -`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(K),E(Me=>Me.filter(Le=>Le!==K)),I(Me=>{const Le=new Set(Me);return Le.delete(K),Le}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),X=w.useCallback(async(K,he,_e)=>{const Me=Ri.get(K);if(!Me||Ri.has(he)||!(await j.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,..._e??{}})})).ok)return!1;Ri.delete(K),Ri.set(he,Me);try{const He=Me.serialize.serialize();await mf(K),await sl(he,He)}catch{}return E(He=>He.map(ke=>ke===K?he:ke)),I(He=>{if(!He.has(K))return He;const ke=new Set(He);return ke.delete(K),ke.add(he),ke}),(Me.connected||Me.ws)&&(await j.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),Y.current(he,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=X),()=>{h&&(h.current=null)}),[h,X]),w.useEffect(()=>{if(t){if(F){A(null);return}if(G){A(null);return}Ri.has(t)?A(t):j.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Ri.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,F,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Me=_e.serialize.serialize();sl(he,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of Ri){try{const _e=he.serialize.serialize();sl(K,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),j.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const se=t?N.has(t):!1,le=D.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!le&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[D.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):V(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>ie(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),le&&!F&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Up," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:lv}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(lv),be(!0),setTimeout(()=>be(!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:fe?"Copied!":"Copy"})]})]})]})}),G&&!F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){ne(!0);try{await(v==null?void 0:v())}finally{ne(!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:B?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=te;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;ie(null);try{(await j.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(V(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),se&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>M(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>M(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function sN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const aN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,lN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN={};function cv(e,t){return(oN.jsx?lN:aN).test(e)}const cN=/[ \t\n\f\r]/g;function uN(e){return typeof e=="object"?e.type==="text"?uv(e.value):!1:uv(e)}function uv(e){return e.replace(cN,"")===""}class qo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}qo.prototype.normal={};qo.prototype.property={};qo.prototype.space=void 0;function k0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new qo(i,s,t)}function Cp(e){return e.toLowerCase()}class En{constructor(t,i){this.attribute=i,this.property=t}}En.prototype.attribute="";En.prototype.booleanish=!1;En.prototype.boolean=!1;En.prototype.commaOrSpaceSeparated=!1;En.prototype.commaSeparated=!1;En.prototype.defined=!1;En.prototype.mustUseProperty=!1;En.prototype.number=!1;En.prototype.overloadedBoolean=!1;En.prototype.property="";En.prototype.spaceSeparated=!1;En.prototype.space=void 0;let hN=0;const ot=va(),yi=va(),kp=va(),ve=va(),Yt=va(),hl=va(),In=va();function va(){return 2**++hN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:yi,commaOrSpaceSeparated:In,commaSeparated:hl,number:ve,overloadedBoolean:kp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class Jp extends En{constructor(t,i,s,a){let o=-1;if(super(t,i),hv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&gN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(dv,bN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!dv.test(o)){let c=o.replace(mN,_N);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Jp}return new a(s,t)}function _N(e){return"-"+e.toLowerCase()}function bN(e){return e.charAt(1).toUpperCase()}const vN=k0([E0,dN,T0,A0,R0],"html"),em=k0([E0,fN,T0,A0,R0],"svg");function yN(e){return e.join(" ").trim()}var al={},xf,fv;function SN(){if(fv)return xf;fv=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=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(D,E){if(typeof D!="string")throw new TypeError("First argument must be a string");if(!D)return[];E=E||{};var N=1,I=1;function te(Y){var U=Y.match(t);U&&(N+=U.length);var A=Y.lastIndexOf(p);I=~A?Y.length-A:I+Y.length}function q(){var Y={line:N,column:I};return function(U){return U.position=new R(Y),be(),U}}function R(Y){this.start=Y,this.end={line:N,column:I},this.source=E.source}R.prototype.content=D;function ie(Y){var U=new Error(E.source+":"+N+":"+I+": "+Y);if(U.reason=Y,U.filename=E.source,U.line=N,U.column=I,U.source=D,!E.silent)throw U}function fe(Y){var U=Y.exec(D);if(U){var A=U[0];return te(A),D=D.slice(A.length),U}}function be(){fe(i)}function B(Y){var U;for(Y=Y||[];U=ne();)U!==!1&&Y.push(U);return Y}function ne(){var Y=q();if(!(f!=D.charAt(0)||_!=D.charAt(1))){for(var U=2;x!=D.charAt(U)&&(_!=D.charAt(U)||f!=D.charAt(U+1));)++U;if(U+=2,x===D.charAt(U-1))return ie("End of comment missing");var A=D.slice(2,U-2);return I+=2,te(A),D=D.slice(U),I+=2,Y({type:b,comment:A})}}function F(){var Y=q(),U=fe(s);if(U){if(ne(),!fe(a))return ie("property missing ':'");var A=fe(o),z=Y({type:v,property:j(U[0].replace(e,x)),value:A?j(A[0].replace(e,x)):x});return fe(c),z}}function G(){var Y=[];B(Y);for(var U;U=F();)U!==!1&&(Y.push(U),B(Y));return Y}return be(),G()}function j(D){return D?D.replace(h,x):x}return xf=S,xf}var pv;function wN(){if(pv)return al;pv=1;var e=al&&al.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(al,"__esModule",{value:!0}),al.default=i;const t=e(SN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return al}var go={},mv;function CN(){if(mv)return go;mv=1,Object.defineProperty(go,"__esModule",{value:!0}),go.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return go.camelCase=p,go}var xo,gv;function kN(){if(gv)return xo;gv=1;var e=xo&&xo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(wN()),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,xo=s,xo}var EN=kN();const NN=Pu(EN),D0=M0("end"),tm=M0("start");function M0(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 B0(e){const t=tm(e),i=D0(e);if(t&&i)return{start:t,end:i}}function To(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?xv(e.position):"start"in e||"end"in e?xv(e):"line"in e||"column"in e?Np(e):""}function Np(e){return _v(e&&e.line)+":"+_v(e&&e.column)}function xv(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function _v(e){return e&&typeof e=="number"?e:1}class an 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=To(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}}an.prototype.file="";an.prototype.name="";an.prototype.reason="";an.prototype.message="";an.prototype.stack="";an.prototype.column=void 0;an.prototype.line=void 0;an.prototype.ancestors=void 0;an.prototype.cause=void 0;an.prototype.fatal=void 0;an.prototype.place=void 0;an.prototype.ruleId=void 0;an.prototype.source=void 0;const im={}.hasOwnProperty,jN=new Map,TN=/[A-Z]/g,AN=new Set(["table","tbody","thead","tfoot","tr"]),RN=new Set(["td","th"]),L0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function DN(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=HN(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=IN(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"?em:vN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=O0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function O0(e,t,i){if(t.type==="element")return MN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return BN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return ON(e,t,i);if(t.type==="mdxjsEsm")return LN(e,t);if(t.type==="root")return zN(e,t,i);if(t.type==="text")return PN(e,t)}function MN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=P0(e,t.tagName,!1),c=UN(e,t);let h=rm(e,t);return AN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!uN(p):!0})),z0(e,c,o,t),nm(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)}Oo(e,t.position)}function LN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Oo(e,t.position)}function ON(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:P0(e,t.name,!0),c=$N(e,t),h=rm(e,t);return z0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function zN(e,t,i){const s={};return nm(s,rm(e,t)),e.create(t,e.Fragment,s,i)}function PN(e,t){return t.value}function z0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function nm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function IN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function HN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=tm(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 UN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&im.call(t.properties,a)){const o=FN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&RN.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 $N(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 Oo(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 Oo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function rm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:jN;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?(Hn(e,e.length,0,t),e):t}const yv={}.hasOwnProperty;function H0(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 fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const pn=$s(/[A-Za-z]/),sn=$s(/[\dA-Za-z]/),QN=$s(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=$s(/\d/),JN=$s(/[\dA-Fa-f]/),e5=$s(/[!-/:-@[-`{-~]/);function Ye(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 Fu=$s(new RegExp("\\p{P}|\\p{S}","u")),_a=$s(/\s/);function $s(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function vl(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 kt(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 ie=t.events.length;let fe=ie,be,B;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(be){B=t.events[fe][1].end;break}be=!0}for(E(s),R=ie;RI;){const q=i[te];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function N(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function s5(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ml(e){if(e===null||qt(e)||_a(e))return 1;if(Fu(e))return 2}function qu(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};wv(x,-p),wv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Hn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&xt(R)?kt(e,N,"linePrefix",o+1)(R):N(R)}function N(R){return R===null||Ye(R)?e.check(Cv,j,te)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),N(R)):(e.consume(R),I)}function te(R){return e.exit("codeFenced"),t(R)}function q(R,ie,fe){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),ne}function ne(U){return R.enter("codeFencedFence"),xt(U)?kt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),G(U)):fe(U)}function G(U){return U===h?(be++,R.consume(U),G):be>=c?(R.exit("codeFencedFenceSequence"),xt(U)?kt(R,Y,"whitespace")(U):Y(U)):fe(U)}function Y(U){return U===null||Ye(U)?(R.exit("codeFencedFence"),ie(U)):fe(U)}}}function x5(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 bf={name:"codeIndented",tokenize:b5},_5={partial:!0,tokenize:v5};function b5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(_5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function v5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(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):Ye(c)?a(c):i(c)}}const y5={name:"codeText",previous:w5,resolve:S5,tokenize:C5};function S5(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&&_o(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),_o(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),_o(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 G0(e,t,i,s,a,o,c,h,p){const f=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||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),j(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function j(E){return!_&&(E===null||E===41||qt(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):Ye(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||Ye(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 K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ao(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const D5={name:"definition",tokenize:B5},M5={partial:!0,tokenize:L5};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 Y0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=fr(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)?Ao(e,f)(v):f(v)}function f(v){return G0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(M5,x,x)(v)}function x(v){return xt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function L5(e,t,i){return s;function s(h){return qt(h)?Ao(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const O5={name:"hardBreakEscape",tokenize:z5};function z5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const P5={name:"headingAtx",resolve:I5,tokenize:H5};function I5(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"},Hn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function H5(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||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):xt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const U5=["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"],Ev=["pre","script","style","textarea"],$5={concrete:!0,name:"htmlFlow",resolveTo:W5,tokenize:G5},F5={partial:!0,tokenize:K5},q5={partial:!0,tokenize:Y5};function W5(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 G5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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,j):C===63?(e.consume(C),a=3,s.interrupt?t:T):pn(C)?(e.consume(C),c=String.fromCharCode(C),D):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):pn(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 S(C){const X="CDATA[";return C===X.charCodeAt(h++)?(e.consume(C),h===X.length?s.interrupt?t:F:S):i(C)}function j(C){return pn(C)?(e.consume(C),c=String.fromCharCode(C),D):i(C)}function D(C){if(C===null||C===47||C===62||qt(C)){const X=C===47,se=c.toLowerCase();return!X&&!o&&Ev.includes(se)?(a=1,s.interrupt?t(C):F(C)):U5.includes(c.toLowerCase())?(a=6,X?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?N(C):I(C))}return C===45||sn(C)?(e.consume(C),c+=String.fromCharCode(C),D):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function N(C){return xt(C)?(e.consume(C),N):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||pn(C)?(e.consume(C),te):xt(C)?(e.consume(C),I):B(C)}function te(C){return C===45||C===46||C===58||C===95||sn(C)?(e.consume(C),te):q(C)}function q(C){return C===61?(e.consume(C),R):xt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ie):xt(C)?(e.consume(C),R):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,be):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),fe)}function be(C){return C===47||C===62||xt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),ne):i(C)}function ne(C){return C===null||Ye(C)?F(C):xt(C)?(e.consume(C),ne):i(C)}function F(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),M):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),ge):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(F5,V,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),F)}function G(C){return e.check(q5,Y,V)(C)}function Y(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),F(C))}function A(C){return C===45?(e.consume(C),T):F(C)}function z(C){return C===47?(e.consume(C),c="",$):F(C)}function $(C){if(C===62){const X=c.toLowerCase();return Ev.includes(X)?(e.consume(C),M):F(C)}return pn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):F(C)}function ge(C){return C===93?(e.consume(C),T):F(C)}function T(C){return C===62?(e.consume(C),M):C===45&&a===2?(e.consume(C),T):F(C)}function M(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),V(C)):(e.consume(C),M)}function V(C){return e.exit("htmlFlow"),t(C)}}function Y5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Wo,t,i)}}const V5={name:"htmlText",tokenize:X5};function X5(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),f):T===47?(e.consume(T),q):T===63?(e.consume(T),I):pn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):pn(T)?(e.consume(T),N):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):Ye(T)?(c=x,z(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const M="CDATA[";return T===M.charCodeAt(o++)?(e.consume(T),o===M.length?j:S):i(T)}function j(T){return T===null?i(T):T===93?(e.consume(T),D):Ye(T)?(c=j,z(T)):(e.consume(T),j)}function D(T){return T===93?(e.consume(T),E):j(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):j(T)}function N(T){return T===null||T===62?A(T):Ye(T)?(c=N,z(T)):(e.consume(T),N)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,z(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function q(T){return pn(T)?(e.consume(T),R):i(T)}function R(T){return T===45||sn(T)?(e.consume(T),R):ie(T)}function ie(T){return Ye(T)?(c=ie,z(T)):xt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||sn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?be(T):i(T)}function be(T){return T===47?(e.consume(T),A):T===58||T===95||pn(T)?(e.consume(T),B):Ye(T)?(c=be,z(T)):xt(T)?(e.consume(T),be):A(T)}function B(T){return T===45||T===46||T===58||T===95||sn(T)?(e.consume(T),B):ne(T)}function ne(T){return T===61?(e.consume(T),F):Ye(T)?(c=ne,z(T)):xt(T)?(e.consume(T),ne):be(T)}function F(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):Ye(T)?(c=F,z(T)):xt(T)?(e.consume(T),F):(e.consume(T),Y)}function G(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=G,z(T)):(e.consume(T),G)}function Y(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?be(T):(e.consume(T),Y)}function U(T){return T===47||T===62||qt(T)?be(T):i(T)}function A(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"),$}function $(T){return xt(T)?kt(e,ge,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):ge(T)}function ge(T){return e.enter("htmlTextData"),c(T)}}const lm={name:"labelEnd",resolveAll:ej,resolveTo:tj,tokenize:ij},Z5={tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj};function ej(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),xt(f)?kt(e,h,"whitespace")(f):h(f))}}const kn={continuation:{tokenize:mj},exit:xj,name:"list",tokenize:pj},dj={partial:!0,tokenize:_j},fj={partial:!0,tokenize:gj};function pj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Wo,s.interrupt?i:_,e.attempt(dj,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 mj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Wo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(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(fj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(kn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function gj(e,t,i){const s=this;return kt(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 xj(e){e.exit(this.containerState.type)}function _j(e,t,i){const s=this;return kt(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 Nv={name:"setextUnderline",resolveTo:bj,tokenize:vj};function bj(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 vj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),xt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const yj={tokenize:Sj};function Sj(e){const t=this,i=e.attempt(Wo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(N5,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 wj={resolveAll:X0()},Cj=V0("string"),kj=V0("text");function V0(e){return{resolveAll:X0(e==="text"?Ej: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Ij(e,t){let i=-1;const s=[];let a;for(;++inew Set(Ke).add(V))}},he.term.onData(at=>{Ue.readyState===WebSocket.OPEN&&Ue.send(at)}),he.ws=Ue},[e]);w.useEffect(()=>{Y.current=ge},[ge]);const T=w.useCallback(async(V,he)=>{if(!S.current||Ri.has(V))return;const{resume:_e=!1,autoConnect:Me=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const He=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),Ce=new WE,Ue=new XE;He.loadAddon(Ce),He.loadAddon(Ue),He.open(Le);const et={term:He,fit:Ce,serialize:Ue,ws:null,container:Le,observer:null,connected:!1},at=new ResizeObserver(()=>{var Et;const{width:Ke}=Le.getBoundingClientRect();if(!(Ke<50))try{Ce.fit(),((Et=et.ws)==null?void 0:Et.readyState)===WebSocket.OPEN&&et.ws.send(JSON.stringify({type:"resize",cols:He.cols,rows:He.rows}))}catch{}});at.observe(Le),et.observer=at,Ri.set(V,et),E(Ke=>[...Ke,V]);try{const Ke=await rN(V);if(Ke){const Et=lv(Ke);He.write(Et),Et!==Ke&&Qa(V,Et).catch(()=>{})}}catch{}Me?ge(V,et,_e):I(Ke=>new Set(Ke).add(V)),setTimeout(()=>U(et),50)},[ge,U]),D=w.useCallback(async(V,he)=>{const _e=Ri.get(V);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),ge(V,_e,he))},[ge]),K=w.useCallback(V=>{const he=Ri.get(V);if(he){try{const _e=he.serialize.serialize();Qa(V,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(V),E(_e=>_e.filter(Me=>Me!==V)),I(_e=>{const Me=new Set(_e);return Me.delete(V),Me}),i(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(V)}},[i,a]),C=w.useCallback(V=>{var _e;const he=Ri.get(V);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),pf(V).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(V),E(Me=>Me.filter(Le=>Le!==V)),I(Me=>{const Le=new Set(Me);return Le.delete(V),Le}),i(`/api/terminal/${encodeURIComponent(V)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(V))},[i,a]),X=w.useCallback(async(V,he,_e)=>{const Me=Ri.get(V);if(!Me||Ri.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:V,newName:he,..._e??{}})})).ok)return!1;Ri.delete(V),Ri.set(he,Me);try{const He=Me.serialize.serialize();await pf(V),await Qa(he,He)}catch{}return E(He=>He.map(Ce=>Ce===V?he:Ce)),I(He=>{if(!He.has(V))return He;const Ce=new Set(He);return Ce.delete(V),Ce.add(he),Ce}),(Me.connected||Me.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),Y.current(he,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=X),()=>{h&&(h.current=null)}),[h,X]),w.useEffect(()=>{if(t){if(F){A(null);return}if(G){A(null);return}Ri.has(t)?A(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(V=>V.ok?V.json():null).then(V=>{if(!Ri.has(t)){const he=(V==null?void 0:V.sessionId)&&!(V!=null&&V.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,F,G]),w.useEffect(()=>{const V=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Me=_e.serialize.serialize();Qa(he,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(V)},[]),w.useEffect(()=>()=>{for(const[V,he]of Ri){try{const _e=he.serialize.serialize();Qa(V,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const re=t?j.has(t):!1,le=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!le&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(V=>d.jsxs("div",{onClick:()=>s==null?void 0:s(V),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${V===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${j.has(V)?"bg-amber-500":V===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${V.startsWith("_new_")?"italic":""}`,children:V.startsWith("_new_")?"Untitled":V}),d.jsx("button",{onClick:he=>{he.stopPropagation(),V.startsWith("_new_")?q(V):K(V)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},V)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>ie(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),le&&!F&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):wu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[$p," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),be(!0),setTimeout(()=>be(!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:fe?"Copied!":"Copy"})]})]})]})}),G&&!F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){ne(!0);try{await(v==null?void 0:v())}finally{ne(!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:B?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const V=te;q(null),C(V)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const V=R;ie(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:V})})).ok&&(K(V),o==null||o(V))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),re&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class $o{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}$o.prototype.normal={};$o.prototype.property={};$o.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new $o(i,s,t)}function wp(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 dN=0;const ot=ga(),Si=ga(),Cp=ga(),ve=ga(),Yt=ga(),rl=ga(),Un=ga();function ga(){return 2**++dN}const kp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Si,commaOrSpaceSeparated:Un,commaSeparated:rl,number:ve,overloadedBoolean:Cp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),mf=Object.keys(kp);class em extends Nn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=em}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),tm=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var Ja={},gf,pv;function wN(){if(pv)return gf;pv=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=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var j=1,I=1;function te(Y){var U=Y.match(t);U&&(j+=U.length);var A=Y.lastIndexOf(p);I=~A?Y.length-A:I+Y.length}function q(){var Y={line:j,column:I};return function(U){return U.position=new R(Y),be(),U}}function R(Y){this.start=Y,this.end={line:j,column:I},this.source=E.source}R.prototype.content=M;function ie(Y){var U=new Error(E.source+":"+j+":"+I+": "+Y);if(U.reason=Y,U.filename=E.source,U.line=j,U.column=I,U.source=M,!E.silent)throw U}function fe(Y){var U=Y.exec(M);if(U){var A=U[0];return te(A),M=M.slice(A.length),U}}function be(){fe(i)}function B(Y){var U;for(Y=Y||[];U=ne();)U!==!1&&Y.push(U);return Y}function ne(){var Y=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var U=2;x!=M.charAt(U)&&(_!=M.charAt(U)||f!=M.charAt(U+1));)++U;if(U+=2,x===M.charAt(U-1))return ie("End of comment missing");var A=M.slice(2,U-2);return I+=2,te(A),M=M.slice(U),I+=2,Y({type:b,comment:A})}}function F(){var Y=q(),U=fe(s);if(U){if(ne(),!fe(a))return ie("property missing ':'");var A=fe(o),z=Y({type:v,property:N(U[0].replace(e,x)),value:A?N(A[0].replace(e,x)):x});return fe(c),z}}function G(){var Y=[];B(Y);for(var U;U=F();)U!==!1&&(Y.push(U),B(Y));return Y}return be(),G()}function N(M){return M?M.replace(h,x):x}return gf=S,gf}var mv;function CN(){if(mv)return Ja;mv=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(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return Ja}var po={},gv;function kN(){if(gv)return po;gv=1,Object.defineProperty(po,"__esModule",{value:!0}),po.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return po.camelCase=p,po}var mo,xv;function EN(){if(xv)return mo;xv=1;var e=mo&&mo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,mo=s,mo}var NN=EN();const jN=Lu(NN),M0=B0("end"),im=B0("start");function B0(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 L0(e){const t=im(e),i=M0(e);if(t&&i)return{start:t,end:i}}function No(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Ep(e):""}function Ep(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Ep(e&&e.start)+"-"+Ep(e&&e.end)}function bv(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=No(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 nm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?tm:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=tm,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=sm(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),rm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}Bo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Bo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=tm,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=sm(e,t);return P0(e,c,o,t),rm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return rm(s,sm(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function rm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=im(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&nm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 Bo(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 Bo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function sm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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 Sv={}.hasOwnProperty;function U0(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 fn=Is(/[A-Za-z]/),nn=Is(/[\dA-Za-z]/),JN=Is(/[#-'*+\--9=?A-Z^-~]/);function Au(e){return e!==null&&(e<32||e===127)}const Np=Is(/\d/),e5=Is(/[\dA-Fa-f]/),t5=Is(/[!-/:-@[-`{-~]/);function Ye(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 Hu=Is(new RegExp("\\p{P}|\\p{S}","u")),pa=Is(/\s/);function Is(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function fl(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 kt(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 ie=t.events.length;let fe=ie,be,B;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(be){B=t.events[fe][1].end;break}be=!0}for(E(s),R=ie;RI;){const q=i[te];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function j(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ol(e){if(e===null||qt(e)||pa(e))return 1;if(Hu(e))return 2}function Uu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=ar(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=ar(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=ar(f,Uu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=ar(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=ar(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,$n(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&xt(R)?kt(e,j,"linePrefix",o+1)(R):j(R)}function j(R){return R===null||Ye(R)?e.check(kv,N,te)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),j(R)):(e.consume(R),I)}function te(R){return e.exit("codeFenced"),t(R)}function q(R,ie,fe){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),ne}function ne(U){return R.enter("codeFencedFence"),xt(U)?kt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),G(U)):fe(U)}function G(U){return U===h?(be++,R.consume(U),G):be>=c?(R.exit("codeFencedFenceSequence"),xt(U)?kt(R,Y,"whitespace")(U):Y(U)):fe(U)}function Y(U){return U===null||Ye(U)?(R.exit("codeFencedFence"),ie(U)):fe(U)}}}function _5(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 _f={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(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):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&go(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),go(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),go(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Au(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||qt(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):Ye(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||Ye(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 K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function jo(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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 qt(v)?jo(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return xt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return qt(h)?jo(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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 U5(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||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):xt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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):fn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):fn(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 S(C){const X="CDATA[";return C===X.charCodeAt(h++)?(e.consume(C),h===X.length?s.interrupt?t:F:S):i(C)}function N(C){return fn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||qt(C)){const X=C===47,re=c.toLowerCase();return!X&&!o&&Nv.includes(re)?(a=1,s.interrupt?t(C):F(C)):$5.includes(c.toLowerCase())?(a=6,X?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?j(C):I(C))}return C===45||nn(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function j(C){return xt(C)?(e.consume(C),j):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||fn(C)?(e.consume(C),te):xt(C)?(e.consume(C),I):B(C)}function te(C){return C===45||C===46||C===58||C===95||nn(C)?(e.consume(C),te):q(C)}function q(C){return C===61?(e.consume(C),R):xt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ie):xt(C)?(e.consume(C),R):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,be):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),fe)}function be(C){return C===47||C===62||xt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),ne):i(C)}function ne(C){return C===null||Ye(C)?F(C):xt(C)?(e.consume(C),ne):i(C)}function F(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),ge):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,K,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),F)}function G(C){return e.check(W5,Y,K)(C)}function Y(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),F(C))}function A(C){return C===45?(e.consume(C),T):F(C)}function z(C){return C===47?(e.consume(C),c="",$):F(C)}function $(C){if(C===62){const X=c.toLowerCase();return Nv.includes(X)?(e.consume(C),D):F(C)}return fn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):F(C)}function ge(C){return C===93?(e.consume(C),T):F(C)}function T(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),T):F(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),K(C)):(e.consume(C),D)}function K(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Fo,t,i)}}const X5={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),f):T===47?(e.consume(T),q):T===63?(e.consume(T),I):fn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):fn(T)?(e.consume(T),j):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):Ye(T)?(c=x,z(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const D="CDATA[";return T===D.charCodeAt(o++)?(e.consume(T),o===D.length?N:S):i(T)}function N(T){return T===null?i(T):T===93?(e.consume(T),M):Ye(T)?(c=N,z(T)):(e.consume(T),N)}function M(T){return T===93?(e.consume(T),E):N(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):N(T)}function j(T){return T===null||T===62?A(T):Ye(T)?(c=j,z(T)):(e.consume(T),j)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,z(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function q(T){return fn(T)?(e.consume(T),R):i(T)}function R(T){return T===45||nn(T)?(e.consume(T),R):ie(T)}function ie(T){return Ye(T)?(c=ie,z(T)):xt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||nn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?be(T):i(T)}function be(T){return T===47?(e.consume(T),A):T===58||T===95||fn(T)?(e.consume(T),B):Ye(T)?(c=be,z(T)):xt(T)?(e.consume(T),be):A(T)}function B(T){return T===45||T===46||T===58||T===95||nn(T)?(e.consume(T),B):ne(T)}function ne(T){return T===61?(e.consume(T),F):Ye(T)?(c=ne,z(T)):xt(T)?(e.consume(T),ne):be(T)}function F(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):Ye(T)?(c=F,z(T)):xt(T)?(e.consume(T),F):(e.consume(T),Y)}function G(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=G,z(T)):(e.consume(T),G)}function Y(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?be(T):(e.consume(T),Y)}function U(T){return T===47||T===62||qt(T)?be(T):i(T)}function A(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"),$}function $(T){return xt(T)?kt(e,ge,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):ge(T)}function ge(T){return e.enter("htmlTextData"),c(T)}}const om={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),xt(f)?kt(e,h,"whitespace")(f):h(f))}}const En={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Np(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(vu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Np(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Fo,s.interrupt?i:_,e.attempt(fj,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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Fo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(En,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return kt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return kt(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 jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),xt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Fo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++i0){const Wt=je.tokenStack[je.tokenStack.length-1];(Wt[1]||Tv).call(je,void 0,Wt[0])}for(xe.position={start:Os(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Os(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt0&&(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 Jj(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function eT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=vl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function iT(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 nT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function J0(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 rT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return J0(e,t);const a={src:vl(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 sT(e,t){const i={src:vl(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 aT(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 lT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return J0(e,t);const a={href:vl(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 oT(e,t){const i={href:vl(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 cT(e,t,i){const s=e.all(t),a=i?uT(i):eS(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(;++h0){const Wt=je.tokenStack[je.tokenStack.length-1];(Wt[1]||Av).call(je,void 0,Wt[0])}for(xe.position={start:Ms(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Ms(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=fl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:fl(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 aT(e,t){const i={src:fl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:fl(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 cT(e,t){const i={href:fl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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 hT(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=tm(t.children[1]),p=D0(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 gT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Dv(t.slice(a),a>0,!1)),o.join("")}function Dv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Av||o===Rv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Av||o===Rv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function bT(e,t){const i={type:"text",value:_T(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function vT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const yT={blockquote:Xj,break:Zj,code:Qj,delete:Jj,emphasis:eT,footnoteReference:tT,heading:iT,html:nT,imageReference:rT,image:sT,inlineCode:aT,linkReference:lT,link:oT,listItem:cT,list:hT,paragraph:dT,root:fT,strong:pT,table:mT,tableCell:xT,tableRow:gT,text:bT,thematicBreak:vT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const tS=-1,Wu=0,Ro=1,Bu=2,om=3,cm=4,um=5,hm=6,iS=7,nS=8,Mv=typeof self=="object"?self:globalThis,ST=(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 Wu:case tS:return i(c,a);case Ro:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case om:return i(new Date(c),a);case cm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case um:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case hm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case iS:{const{name:h,message:p}=c;return i(new Mv[h](p),a)}case nS: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 Mv[o](c),a)};return s},Bv=e=>ST(new Map,e)(0),ll="",{toString:wT}={},{keys:CT}=Object,bo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=wT.call(e).slice(8,-1);switch(i){case"Array":return[Ro,ll];case"Object":return[Bu,ll];case"Date":return[om,ll];case"RegExp":return[cm,ll];case"Map":return[um,ll];case"Set":return[hm,ll];case"DataView":return[Ro,i]}return i.includes("Array")?[Ro,i]:i.includes("Error")?[iS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),kT=(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]=bo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=nS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([tS],c)}return a([h,_],c)}case Ro:{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 Bu:{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 CT(c))(e||!cu(bo(c[b])))&&_.push([o(b),o(c[b])]);return x}case om:return a([h,c.toISOString()],c);case cm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case um:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(bo(b))||cu(bo(v))))&&_.push([o(b),o(v)]);return x}case hm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(bo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Lv=(e,{json:t,lossy:i}={})=>{const s=[];return kT(!(t||i),!!t,new Map,s)(e),s},zo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Bv(Lv(e,t)):structuredClone(e):(e,t)=>Bv(Lv(e,t));function ET(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 NT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function jT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||ET,s=e.options.footnoteBackLabel||NT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let N=typeof i=="string"?i:i(p,v);typeof N=="string"&&(N={type:"text",value:N}),S.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(N)?N:[N]})}const D=_[_.length-1];if(D&&D.type==="element"&&D.tagName==="p"){const N=D.children[D.children.length-1];N&&N.type==="text"?N.value+=" ":D.children.push({type:"text",value:" "}),D.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...zo(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`});const f={type:"element",tagName:"li",properties:o,children:c};return e.patch(t,f),e.applyData(t,f)}function hT(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const i=e.children;let s=-1;for(;!t&&++s1}function dT(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=im(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:su,yaml:su,definition:su,footnoteDefinition:su};function su(){}const iS=-1,$u=0,To=1,Ru=2,cm=3,um=4,hm=5,dm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 $u:case iS:return i(c,a);case To:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Ru:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case cm:return i(new Date(c),a);case um:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case hm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case dm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),el="",{toString:CT}={},{keys:kT}=Object,xo=e=>{const t=typeof e;if(t!=="object"||!e)return[$u,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[To,el];case"Object":return[Ru,el];case"Date":return[cm,el];case"RegExp":return[um,el];case"Map":return[hm,el];case"Set":return[dm,el];case"DataView":return[To,i]}return i.includes("Array")?[To,i]:i.includes("Error")?[nS,i]:[Ru,i]},au=([e,t])=>e===$u&&(t==="function"||t==="symbol"),ET=(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]=xo(c);switch(h){case $u:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case To:{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 Ru:{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 kT(c))(e||!au(xo(c[b])))&&_.push([o(b),o(c[b])]);return x}case cm:return a([h,c.toISOString()],c);case um:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case hm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(au(xo(b))||au(xo(v))))&&_.push([o(b),o(v)]);return x}case dm:{const _=[],x=a([h,_],c);for(const b of c)(e||!au(xo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Lo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let j=typeof i=="string"?i:i(p,v);typeof j=="string"&&(j={type:"text",value:j}),S.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(j)?j:[j]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const j=M.children[M.children.length-1];j&&j.type==="text"?j.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Lo(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 Gu=(function(e){if(e==null)return DT;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?TT(e):AT(e);if(typeof e=="string")return RT(e);throw new Error("Expected function, string, or object as test")});function TT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=rS,S,j,D;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=OT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==LT)for(j=(s?E.children.length:-1)+c,D=_.concat(E);j>-1&&j":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Tp))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` -`}),i}function Ov(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function zv(e,t){const i=PT(e,t),s=i.one(e,void 0),a=jT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function FT(e,t){return e&&"run"in e?async function(i,s){const a=zv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return zv(i,{file:s,...e||t})}}function Pv(e){if(e)throw e}var yf,Iv;function qT(){if(Iv)return yf;Iv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,j=arguments[0],D=1,E=arguments.length,N=!1;for(typeof j=="boolean"&&(N=j,j=arguments[1]||{},D=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});Dc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:VT,extname:XT,join:ZT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Go(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 VT(e){if(Go(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 XT(e){Go(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 ZT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function JT(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 Go(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const eA={cwd:tA};function tA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function iA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 nA(e)}function nA(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,...S]=_;const j=s[b][1];Dp(j)&&Dp(v)&&(v=Sf(!0,j,v)),s[b]=[f,v,...S]}}}}const lA=new fm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 Uv(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function $v(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return oA(e)?e:new aS(e)}function oA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function cA(e){return typeof e=="string"||uA(e)}function uA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const hA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Fv=[],qv={allowDangerousHtml:!0},dA=/^(https?|ircs?|mailto|xmpp)$/i,fA=[{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 lS(e){const t=pA(e),i=mA(e);return gA(t.runSync(t.parse(i),i),e)}function pA(e){const t=e.rehypePlugins||Fv,i=e.remarkPlugins||Fv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...qv}:qv;return lA().use(Vj).use(i).use(FT,s).use(t)}function mA(e){const t=e.children||"",i=new aS;return typeof t=="string"&&(i.value=t),i}function gA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||xA;for(const _ of fA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+hA+_.id,void 0);return dm(e,f),DN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],j=_f[v];(j===null||j.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 xA(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||dA.test(e.slice(0,t))?e:""}function _A(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function oS(e,t,i){const a=Gu((i||{}).ignore||[]),o=bA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=te+1:(S!==te&&N.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(R)?N.push(...R):R&&N.push(R),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Wv(e,"(");let o=Wv(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 uS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||_a(i)||Fu(i))&&(!t||i!==47)}hS.peek=qA;function OA(){this.buffer()}function zA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function PA(){this.buffer()}function IA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function HA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function UA(e){this.exit(e)}function $A(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function FA(e){this.exit(e)}function qA(){return"["}function hS(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 WA(){return{enter:{gfmFootnoteCallString:OA,gfmFootnoteCall:zA,gfmFootnoteDefinitionLabelString:PA,gfmFootnoteDefinition:IA},exit:{gfmFootnoteCallString:HA,gfmFootnoteCall:UA,gfmFootnoteDefinitionLabelString:$A,gfmFootnoteDefinition:FA}}}function GA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:hS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?dS:YA))),f(),p}}function YA(e,t,i){return t===0?e:dS(e,t,i)}function dS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];fS.peek=JA;function VA(){return{canContainEols:["delete"],enter:{strikethrough:ZA},exit:{strikethrough:QA}}}function XA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:fS}}}function ZA(e){this.enter({type:"delete",children:[]},e)}function QA(e){this.exit(e)}function fS(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 JA(){return"~"}function eR(e){return e.length}function tR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||eR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}j.push(N)}c[_]=j,h[_]=D}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=N),v[x]=N),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),rR);return a(),c}function rR(e,t,i){return">"+(i?"":" ")+e}function sR(e,t){return Yv(e,t.inConstruct,!0)&&!Yv(e,t.notInConstruct,!1)}function Yv(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 lR(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 oR(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 cR(e,t,i,s){const a=oR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(lR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,uR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(aR(o,a)+1,3)),f=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:` +`}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var vf,Hv;function WT(){if(Hv)return vf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return vf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,j=!1;for(typeof N=="boolean"&&(j=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 Er={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');qo(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 XT(e){if(qo(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 ZT(e){qo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 qo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Dp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Dp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Rp(N)&&Rp(v)&&(v=yf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new pm().freeze();function kf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Nf(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 $v(e){if(!Rp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function lu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return fm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 xf)if(Object.hasOwn(xf,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=xf[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Fu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=te+1:(S!==te&&j.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(R)?j.push(...R):R&&j.push(R),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||pa(i)||Hu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(j)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=j),v[x]=j),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(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 oR(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 cR(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 uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=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),f(),_}function uR(e,t,i){return(i?"":" ")+e}function pm(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 hR(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function dR(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 Po(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=ml(e),a=ml(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}}pS.peek=fR;function pS(e,t,i,s){const a=dR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Po(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Po(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function fR(e,t,i){return i.options.emphasis||"*"}function pR(e,t){let i=!1;return dm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&sm(e)&&(t.options.setext||i))}function mR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(pR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`)),_+=h.move(p),f(),_}function hR(e,t,i){return(i?"":" ")+e}function mm(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 dR(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Oo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Du(e,t,i){const s=ol(e),a=ol(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Du(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Du(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return fm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Tp}),!!((!e.depth||e.depth<3)&&am(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` `,after:` `});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 f=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(f)&&(f=Po(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}mS.peek=gR;function mS(e){return e.value||""}function gR(){return"<"}gS.peek=xR;function gS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function xR(){return"!"}xS.peek=_R;function xS(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function _R(){return"!"}_S.peek=bR;function _S(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))}vS.peek=vR;function vS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(bS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function vR(e,t,i){return bS(e,i)?"<":"["}yS.peek=yR;function yS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function yR(){return"["}function mm(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 SR(e){const t=mm(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 wR(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 SS(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?wR(i):mm(i);const h=e.ordered?c==="."?")":".":SR(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),SS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function NR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const jR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function TR(e,t,i,s){return(e.children.some(function(c){return jR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function AR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}wS.peek=RR;function wS(e,t,i,s){const a=AR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Po(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Po(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function RR(e,t,i){return i.options.strong||"*"}function DR(e,t,i,s){return i.safe(e.value,s)}function MR(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=(SS(i)+(i.options.ruleSpaces?" ":"")).repeat(MR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const CS={blockquote:nR,break:Kv,code:cR,definition:hR,emphasis:pS,hardBreak:Kv,heading:mR,html:mS,image:gS,imageReference:xS,inlineCode:_S,link:vS,linkReference:yS,list:CR,listItem:ER,paragraph:NR,root:TR,strong:wS,text:DR,thematicBreak:BR};function LR(){return{enter:{table:OR,tableData:Vv,tableHeader:Vv,tableRow:PR},exit:{codeText:IR,table:zR,tableData:Df,tableHeader:Df,tableRow:Df}}}function OR(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 zR(e){this.exit(e),this.data.inTable=void 0}function PR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Vv(e){this.enter({type:"tableCell",children:[]},e)}function IR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,HR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function HR(e,t){return t==="|"?t:e}function UR(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,S,j,D){return f(_(v,j,D),v.align)}function h(v,S,j,D){const E=x(v,j,D),N=f([E]);return N.slice(0,N.indexOf(` -`))}function p(v,S,j,D){const E=j.enter("tableCell"),N=j.enter("phrasing"),I=j.containerPhrasing(v,{...D,before:o,after:o});return N(),E(),I}function f(v,S){return tR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,j){const D=v.children;let E=-1;const N=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const s3={tokenize:f3,partial:!0};function a3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:u3,continuation:{tokenize:h3},exit:d3}},text:{91:{name:"gfmFootnoteCall",tokenize:c3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:l3,resolveTo:o3}}}}function l3(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 f=fr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function o3(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 c3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(fr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function u3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=fr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function h3(e,t,i){return e.check(Wo,t,e.attempt(s3,t,i))}function d3(e){e.exit("gfmFootnoteDefinition")}function f3(e,t,i){const s=this;return kt(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 p3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const D=c.exit("strikethroughSequenceTemporary"),E=ml(S);return D._open=!E||E===2&&!!j,D._close=!j||j===2&&!!E,h(S)}}}class m3{constructor(){this.map=[]}add(t,i,s){g3(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 g3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Y=s.events[ne][1].type;if(Y==="lineEnding"||Y==="linePrefix")ne--;else break}const F=ne>-1?s.events[ne][1].type:null,G=F==="tableHead"||F==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):xt(B)?kt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,xt(B)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?D(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),j):q(B)}function j(B){return xt(B)?kt(e,D,"whitespace")(B):D(B)}function D(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?te(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),N(B)):q(B)}function N(B){return B===45?(e.consume(B),N):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return xt(B)?kt(e,te,"whitespace")(B):te(B)}function te(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ie(B)}function ie(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ie):B===null||Ye(B)?(e.exit("tableRow"),t(B)):xt(B)?kt(e,ie,"whitespace")(B):(e.enter("data"),fe(B))}function fe(B){return B===null||B===124||qt(B)?(e.exit("data"),ie(B)):(e.consume(B),B===92?be:fe)}function be(B){return B===92||B===124?(e.consume(B),fe):fe(B)}}function v3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new m3;for(;++ii[2]+1){const S=i[2]+1,j=i[3]-i[2]-1;e.add(S,j,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ol(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Zv(e,t,i,s,a){const o=[],c=ol(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 ol(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const y3={name:"tasklistCheck",tokenize:w3};function S3(){return{text:{91:y3}}}function w3(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 Ye(p)?t(p):xt(p)?e.check({tokenize:C3},t,i)(p):i(p)}}function C3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function k3(e){return H0([XR(),a3(),p3(e),_3(),S3()])}const E3={};function MS(e){const t=this,i=e||E3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(k3(i)),o.push(GR()),c.push(YR(i))}const ha=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],gl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ha,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ha],h2:[["className","sr-only"]],img:[...ha,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ha,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ha],table:[...ha],ul:[...ha,["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"]},Ps={}.hasOwnProperty;function N3(e,t){let i={type:"root",children:[]};const s={schema:t?{...gl,...t}:gl,stack:[]},a=BS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function BS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return j3(e,i);case"doctype":return T3(e,i);case"element":return A3(e,i);case"root":return R3(e,i);case"text":return D3(e,i)}}}function j3(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 Yo(o,t),o}}function T3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Yo(i,t),i}}function A3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=LS(e,t.children),a=M3(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&&Ps.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function zS(e){return function(t){return N3(t,e)}}const dl=["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"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function PS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const O3=Object.fromEntries(dl.map(e=>[PS(e),e])),z3={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 Cu(e){if(!e)return null;const t=PS(e.trim());return t?O3[t]??z3[t]??null:null}function IS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function xm(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(IS(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 ey({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=xm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function ty(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 Eo(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),f=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=j=>{const D=a.hasSpeaker?j*c:0,E=a.hasSpeaker?D*o:0,N=Math.max(1,_-E),I=a.fontWeight??400,te=ty((ie,fe)=>e(ie,fe,I),t,f,j),q=te.length*j*o,R=te.every(ie=>e(ie,j,I)<=f+.5);return{lines:te,ok:q<=N&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const j=Math.max(1,a.fontSize),{lines:D,ok:E}=v(j);return{lines:D,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!E}}for(let j=x;j>=b;j-=.5){const{lines:D,ok:E}=v(j);if(E)return{lines:D,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!1}}return{lines:ty(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function P3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const HS=["speech","narration","sfx"],I3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function fl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function _m(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=fl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=fl(t.lineHeightFactor,.9,2),c=fl(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 Ku(e){if(!e||typeof e!="object")return;const t=e,i=fl(t.paddingX,0,.25),s=fl(t.paddingY,0,.25),a=fl(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 No(e,t,i,s){const{minFontSize:a,maxFontSize:o}=P3(t),c=_m(e.textStyle),h=Ku(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 US(e,t,i){const s=Ku(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function $S(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function iy(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?Ar(e,h,p):t+i/2,half:c}}function bm(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??$S(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:N,half:I}=iy(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:N-I,y:E},base2:{x:N+I,y:E}}}const S=_>=0?e+i:e,{center:j,half:D}=iy(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:j-D},base2:{x:S,y:j+D}}}function H3(e){return e.type!=="speech"||!e.tailAnchor?!1:bm(0,0,1,1,e.tailAnchor)!==null}function U3(e,t,i,s,a,o){const c=o??$S(i,s),h=e+i,p=t+s,f=!!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 f&&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 FS(e,t,i,s,a,o){const c=U3(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 $3(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 ny=0;function Lp(e,t=.1,i=.1){return ny++,{id:`overlay-${Date.now()}-${ny}`,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 qS(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 du=.05;function Ui(e){return typeof e=="number"&&Number.isFinite(e)}function F3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let q3=0;function W3(e){if(!e||typeof e!="object")return null;const t=e,i=HS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ui(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ui(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ui(t.x)&&Ui(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?F3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++q3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Ui(b.x)&&Ui(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=_m(t.textStyle),x=Ku(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function G3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&HS.includes(t.type)&&Ui(t.x)&&Ui(t.y)&&Ui(t.width)&&Ui(t.height)&&typeof t.text=="string"}function Y3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=W3(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),G3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function i4(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=_m(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=Ku(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 ry=new Set(["speech","narration"]),K3=.12;function sy(e){return Ui(e==null?void 0:e.x)&&Ui(e==null?void 0:e.y)&&Ui(e==null?void 0:e.width)&&Ui(e==null?void 0:e.height)&&e.width>0&&e.height>0}function V3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function fn(e){return e.kind==="text"}function X3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||fn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function WS(e,t=I3){return!e.finalImagePath||!(e.overlays??[]).some(H3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ay,height:Math.round(ay*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Z3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ey,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ey,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=X3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function Q3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Z3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const ly=/!\[[^\]]*\]\([^)]*\)/g,J3=//g,YS=200;function eD(e){const t=(e.match(ly)||[]).length,i=e.length,s=e.replace(J3," ").replace(ly," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,YS)}}function tD(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 iD=[/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 nD(e){for(const t of iD){const i=e.match(t);if(i)return i[0]}return null}function vm(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=nD(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 VS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(rD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 sD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function XS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:sD(h)})}return o}const aD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function ym(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 lD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)fn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&lD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const oD={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 vo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function cD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(N=>!_[N]),v=N=>s.needClean>0?vo(N,s.needClean):"no image cuts",S={plan:vo(s.total,s.total),clean:v(s.withClean),letter:vo(s.withText,s.total),export:vo(s.exported,s.total),upload:vo(s.uploaded,s.total),publish:null},j=x.map((N,I)=>({key:N,label:oD[N],status:b===-1||IYS,a=dD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${pD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(lS,{remarkPlugins:[cS,MS],rehypePlugins:[[zS,fD]],children:e})}):d.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 gD="modulepreload",xD=function(e){return"/"+e},oy={},cy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=xD(f),f in oy)return;oy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":gD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Sm=[{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:[]}],_D="system-ui, sans-serif",bD=Sm.find(e=>e.family==="Noto Sans"),vD=Sm.find(e=>e.category==="display");function ZS(e){return Sm.find(i=>i.category==="body"&&i.languages.includes(e))||bD}function QS(){return vD}function JS(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${_D}`}function yD(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 ul(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 SD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ul(e.current)}function wm(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 wD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function uy(e){const t=wm(e);return t.map((i,s)=>{const{x:a,y:o}=wD(i.type,s,t.length),c=Lp(i.type,a,o),h=qS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Cn(e,t){return e*t}function hy(e,t){return t===0?0:e/t}function dy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=JS(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},CD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const fy=.05,kD=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ED({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,ui,Bt,yt,Rt,Qe,hi;const b=ZS(c),v=QS(),S=Ou(b),j=Ou(v);w.useEffect(()=>{dy(b),dy(v)},[b,v]),w.useEffect(()=>{let H=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Se}=await cy(async()=>{const{ensureFontsReady:Oe}=await import("./export-cut-HPHvubLr.js");return{ensureFontsReady:Oe}},[]);await Se([b.family,v.family])}catch{}H||G(!0)})(),()=>{H=!0}},[b.family,v.family]);const D=xm(e,t.cleanImagePath,h),E=w.useMemo(()=>Y3(t.overlays),[t.overlays]),N=E.invalid.length,[I,te]=w.useState(!1),q=N===0&&E.changed&&E.overlays.length>0,[R,ie]=w.useState(()=>E.overlays),[fe,be]=w.useState(()=>ul(E.overlays)),B=w.useRef(null),ne=w.useCallback(H=>(Se,Oe,Ae=400)=>{var Fe;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Fe=B.current)==null?void 0:Fe.getContext("2d");return Ge?(Ge.font=`${Ae} ${Oe}px ${H}`,Ge.measureText(Se).width):Se.length*Oe*.5},[]),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(!1),[$,ge]=w.useState(!1),[T,M]=w.useState(null),[V,C]=w.useState(null),[X,se]=w.useState({x:0,y:0,width:0,height:0}),le=w.useRef(null),K=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const H=le.current;if(!H)return;const Se=H.clientWidth,Oe=H.clientHeight;let Ae,Ge;if(t.kind==="text"){const ct=GS(t.aspectRatio)??{width:800,height:600};Ae=ct.width,Ge=ct.height}else{const ct=K.current;if(!ct||!ct.naturalWidth)return;Ae=ct.naturalWidth,Ge=ct.naturalHeight}if(!Se||!Oe)return;const Fe=Math.min(Se/Ae,Oe/Ge),dt=Ae*Fe,ft=Ge*Fe;se({x:(Se-dt)/2,y:(Oe-ft)/2,width:dt,height:ft})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=le.current;if(!H)return;const Se=new ResizeObserver(()=>_e());return Se.observe(H),()=>Se.disconnect()},[_e]);const Me=w.useCallback(H=>{const Se=qS(H.type,H.x,H.y),Oe=Se.width,Ae=Math.max(.08,1-H.y);if(!H.text||!F||X.width<=0)return Se;const Ge=H.type==="sfx"?j:S,Fe=Cn(Oe,X.width);let dt=H.type==="sfx"?.08:.12;for(let ft=0;ft<24;ft++){const ct=Math.min(dt,Ae),Vt=Cn(ct,X.height);if(!Eo(ne(Ge),H.text,Fe,Vt,No({...H},X.height||300,Fe,Vt)).overflow||ct>=Ae)return{width:Oe,height:ct};dt+=.03}return{width:Oe,height:Math.min(dt,Ae)}},[F,X,ne,S,j]),Le=w.useCallback(H=>{const Se=Lp(H,.1+Math.random()*.3,.1+Math.random()*.3),Oe={...Se,...Me(Se)};ie(Ae=>[...Ae,Oe]),U(Oe.id)},[Me]),He=w.useCallback(H=>{const Oe={...Lp(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},Ae={...Oe,...Me(Oe)};ie(Ge=>[...Ge,Ae]),U(Ae.id)},[Me]),ke=w.useCallback((H,Se)=>{ie(Oe=>Oe.map(Ae=>Ae.id===H?{...Ae,...Se}:Ae))},[]),Ue=w.useCallback(H=>{var dt;const Se=X.height||300,Oe=X.width>0?Cn(H.width,X.width):200,Ae=X.height>0?Cn(H.height,X.height):100,Ge=H.type==="sfx"?j:S,Fe=Eo(ne(Ge),H.text,Oe,Ae,No({...H,textStyle:void 0},Se,Oe,Ae));ke(H.id,{textStyle:{mode:"manual",fontScale:Fe.fontSize/Math.max(1,Se),fontWeight:((dt=H.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Fe.fontSize>0?Fe.lineHeight/Fe.fontSize:1.2,speakerScale:Fe.fontSize>0&&Fe.speakerFontSize>0?Fe.speakerFontSize/Fe.fontSize:.8}})},[X,j,S,ne,ke]),Je=w.useCallback(H=>{ie(Se=>Se.filter(Oe=>Oe.id!==H)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),Ve=w.useCallback((H,Se)=>{H.stopPropagation(),U(Se),z(!1)},[]),Et=w.useCallback((H,Se,Oe)=>{H.stopPropagation(),H.preventDefault();const Ae=R.find(Ge=>Ge.id===Se);Ae&&(U(Se),he.current={id:Se,mode:Oe,startX:H.clientX,startY:H.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const H=Oe=>{const Ae=he.current;if(!Ae||X.width===0)return;const Ge=hy(Oe.clientX-Ae.startX,X.width),Fe=hy(Oe.clientY-Ae.startY,X.height);if(Ae.mode==="move"){const dt=pu(Ae.origX+Ge,0,1-Ae.origW),ft=pu(Ae.origY+Fe,0,1-Ae.origH);ke(Ae.id,{x:dt,y:ft})}else{const dt=pu(Ae.origW+Ge,fy,1-Ae.origX),ft=pu(Ae.origH+Fe,fy,1-Ae.origY);ke(Ae.id,{width:dt,height:ft})}},Se=()=>{he.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",Se),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",Se)}},[X,ke]);const ze=w.useCallback(async()=>{var H;C(null);try{const Se=ul(R),Oe=((H=t.aiDraft)==null?void 0:H.status)==="generated"&&Se!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Oe??null),f&&a()}catch(Se){C(Se instanceof Error?Se.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),_t=w.useCallback(async()=>{if(N>0&&!I){const H=N;M(`${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}ge(!0),M(null);try{await s(R);const{exportCut:H,ensureFontsReady:Se}=await cy(async()=>{const{exportCut:pt,ensureFontsReady:Fi}=await import("./export-cut-HPHvubLr.js");return{exportCut:pt,ensureFontsReady:Fi}},[]),Oe=R.some(pt=>pt.type==="sfx"),Ae=[b.family,...Oe?[v.family]:[]],{ready:Ge,missing:Fe}=await Se(Ae);if(!Ge){M(`Fonts not loaded: ${Fe.join(", ")}. Check your connection and retry.`),ge(!1);return}if(t.cleanImagePath&&!D.url){M(D.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),ge(!1);return}const dt=D.url,ft=await H(dt,R,S,j,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),ct=new FormData,Vt=ft.type==="image/webp"?"webp":"jpg";ct.append("file",ft,`cut-${t.id}.${Vt}`);const Ci=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:ct});if(Ci.ok)be(ul(R)),o==null||o();else{const pt=await Ci.json();M(pt.error||"Export failed")}}catch(H){M(H instanceof Error?H.message:"Export failed")}finally{ge(!1)}},[t,D,R,e,i,b,v,S,j,h,s,o,N,I]),Te=R.find(H=>H.id===Y),Kt=w.useMemo(()=>V3(R),[R]),mi=w.useRef(t.id);w.useEffect(()=>{mi.current!==t.id&&(mi.current=t.id,be(ul(E.overlays)))},[t.id,E.overlays]);const wt=SD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:R}),et=w.useMemo(()=>yD({...t,overlays:R},{staleExport:wt}),[t,R,wt]),Q=w.useMemo(()=>wm(t),[t]),xe=w.useMemo(()=>{const H={};for(const Se of R){const Oe=$3(Se);let Ae=!1;if(F&&X.width>0&&Se.text){const Ge=Se.type==="sfx"?j:S,Fe=Cn(Se.width,X.width),dt=Cn(Se.height,X.height);Ae=Eo(ne(Ge),Se.text,Fe,dt,No(Se,X.height||300,Fe,dt)).overflow}(Oe||Ae)&&(H[Se.id]={outOfBounds:Oe,overflow:Ae})}return H},[R,F,X,ne,S,j]),je=Object.keys(xe).length,$e=t.kind==="text",nt=!t.cleanImagePath;return!$e&&nt&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),V&&d.jsx("span",{className:"text-[10px] text-error",children:V}),d.jsx("button",{onClick:_t,disabled:$,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:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{ze()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),N>0&&!I?d.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:[d.jsxs("span",{children:[N," overlay",N===1?"":"s"," ","from the cut plan ",N===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",N===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",N," unplaceable overlay",N===1?"":"s"]})]}):N>0?d.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 ",N," unplaceable overlay",N===1?"":"s"," — the export will not include"," ",N===1?"it":"them","."]}):q?d.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,Kt.length>0&&d.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,": ",Kt.length," bubble"," ",Kt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Kt.map(H=>`#${H.indexA+1} ${Lf(R[H.indexA])} ↔ #${H.indexB+1} ${Lf(R[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",et.hasCleanImage],["script-text","Script text",et.hasScriptText],["bubbles",`Bubbles placed${et.bubblesPlaced?` (${et.bubblesPlaced})`:""}`,et.bubblesPlaced>0],["exported","Final exported",et.exported],["uploaded","Uploaded",et.uploaded]].map(([H,Se,Oe])=>d.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Oe?"true":"false",className:`flex items-center gap-1 ${Oe?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Oe?"✓":"○"}),Se]},H))}),wt&&d.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."}),je>0&&d.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:[je," bubble",je===1?"":"s"," may not export cleanly:"," ",Object.entries(xe).map(([H,Se])=>{const Oe=R.findIndex(Ge=>Ge.id===H),Ae=[Se.outOfBounds?"outside image":null,Se.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Oe+1} ${Lf(R[Oe])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:le,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&D.error?d.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&&!D.url?d.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?d.jsx("img",{ref:K,src:D.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):$e?X.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:X.x,top:X.y,width:X.width,height:X.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&X.width===0){const Se=H.getBoundingClientRect();Se.width>0&&se({x:0,y:0,width:Se.width,height:Se.height})}},children:"Narration cut"}),X.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(H=>{if(H.type!=="speech")return null;const Se=X.x+Cn(H.x,X.width),Oe=X.y+Cn(H.y,X.height),Ae=Cn(H.width,X.width),Ge=Cn(H.height,X.height),Fe=US(H,Ae,Ge),dt=H.tailAnchor?bm(Se,Oe,Ae,Ge,H.tailAnchor,Fe):null,ft=Math.max(1.5,X.height*.004),ct=H.id===Y;return d.jsx("path",{"data-testid":`balloon-${H.id}`,d:FS(Se,Oe,Ae,Ge,dt,Fe),className:`fill-white/95 ${ct?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:ct?ft+.5:ft,strokeLinejoin:"round"},H.id)})}),X.width>0&&R.map(H=>{const Se=X.x+Cn(H.x,X.width),Oe=X.y+Cn(H.y,X.height),Ae=Cn(H.width,X.width),Ge=Cn(H.height,X.height),Fe=H.id===Y,dt=H.type==="speech",ft=H.type==="narration",ct=!!xe[H.id];return d.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":ct?"true":"false",onClick:Vt=>Ve(Vt,H.id),onMouseDown:Vt=>Et(Vt,H.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${CD[H.type]}`} ${ft?"bg-[#f4efe6]/85 rounded-md":""} ${Fe&&!dt?"ring-2 ring-accent":""} ${ct?"ring-2 ring-amber-500":""}`,style:{left:Se,top:Oe,width:Ae,height:Ge},children:[(()=>{var Fi,Nn;const Vt=H.type==="sfx"?j:S;if(!H.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Vt},children:ku[H.type]});const Ci=H.type!=="sfx"&&!!H.speaker;if(!F)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Vt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((Fi=H.textStyle)==null?void 0:Fi.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:Ci?`${H.speaker}: ${H.text}`:H.text});const pt=Eo(ne(Vt),H.text,Ae,Ge,No(H,X.height,Ae,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Vt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[Ci&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:pt.speakerFontSize,lineHeight:1.2},children:H.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:pt.fontSize,lineHeight:`${pt.lineHeight}px`,fontWeight:((Nn=H.textStyle)==null?void 0:Nn.fontWeight)??400},children:pt.lines.map((ln,Un)=>d.jsx("span",{className:"block",children:ln},Un))})]})})(),Fe&&d.jsx("div",{onMouseDown:Vt=>{Vt.stopPropagation(),Et(Vt,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)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((ui=t.aiDraft)==null?void 0:ui.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(H=>d.jsxs("button",{onClick:()=>He(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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[H.type]]})," ",d.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:H=>ke(Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:H=>ke(Te.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"})]}),d.jsx("button",{onClick:()=>ke(Te.id,Me(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Bt=Te.textStyle)==null?void 0:Bt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>ke(Te.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"}):d.jsx("button",{type:"button",onClick:()=>Ue(Te),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"})]}),((yt=Te.textStyle)==null?void 0:yt.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>ke(Te.id,{textStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:H=>ke(Te.id,{textStyle:{...Te.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>ke(Te.id,{textStyle:{...Te.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:H=>ke(Te.id,{textStyle:{...Te.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const H=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:kD.map(Se=>d.jsx("button",{type:"button",onClick:()=>ke(Te.id,{tailAnchor:Se.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-${Se.key}`,children:Se.label},Se.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:Se=>ke(Te.id,{tailAnchor:{...H,x:parseFloat(Se.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:Se=>ke(Te.id,{tailAnchor:{...H,y:parseFloat(Se.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Rt=Te.bubbleStyle)==null?void 0:Rt.paddingX)??.06)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Qe=Te.bubbleStyle)==null?void 0:Qe.paddingY)??.08)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((hi=Te.bubbleStyle)==null?void 0:hi.cornerRadius)??.4)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?Je(Te.id):z(!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:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function py(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=JS(e),document.head.appendChild(i)}function ND({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=ZS(o),b=QS(),v=Ou(x),S=Ou(b),j=xm(e,t,i),D=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[N,I]=w.useState(!1),[te,q]=w.useState(()=>GS(h)??{width:800,height:600}),[R,ie]=w.useState({width:0,height:0});w.useEffect(()=>{py(x),py(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var ne;try{(ne=document.fonts)!=null&&ne.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=D.current;if(!B)return;const ne=new ResizeObserver(()=>{ie({width:B.clientWidth,height:B.clientHeight})});return ne.observe(B),()=>ne.disconnect()},[]);const fe=w.useCallback(B=>(ne,F,G=400)=>E?(E.font=`${G} ${F}px ${B}`,E.measureText(ne).width):ne.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:D,style:{aspectRatio:`${te.width} / ${te.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?j.error||!j.loading&&!j.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):j.url?d.jsx("img",{src:j.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const ne=B.currentTarget.naturalWidth||te.width,F=B.currentTarget.naturalHeight||te.height;ne>0&&F>0&&q({width:ne,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=US(B,G,Y),A=B.tailAnchor?bm(ne,F,G,Y,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:FS(ne,F,G,Y,A,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var $;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=B.type==="sfx"?S:v,A=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${A?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:ne,top:F,width:G,height:Y},children:B.text?N?(()=>{var T;const ge=Eo(fe(U),B.text,G,Y,No(B,R.height,G,Y));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:ge.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ge.fontSize,lineHeight:`${ge.lineHeight}px`,fontWeight:((T=B.textStyle)==null?void 0:T.fontWeight)??400},children:ge.lines.map((M,V)=>d.jsx("span",{className:"block",children:M},V))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(Y*.05,14)),fontWeight:(($=B.textStyle)==null?void 0:$.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const jD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},TD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",AD="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 RD(e){var a;const t=jD[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(AD),s.push(TD),s.join(` -`).trim()}function DD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function my(e,t){const i=DD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",RD(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(` -`)}const e1=12e3,MD=5,BD=6e4,LD=6e4,OD=5;function zD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function PD(e,t=e1){return Math.min(t*2**e,BD)}const t1=e=>new Promise(t=>setTimeout(t,e));async function ID(e,t={}){var c;const i=t.sleep??t1,s=t.maxRetries??MD,a=t.baseDelayMs??e1;let o=0;for(;;){const h=await e();if(h.ok||!zD(h.status,h.errorMessage)||o>=s)return h;const p=PD(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function HD(e={}){const t=e.limit??OD,i=e.windowMs??LD,s=e.sleep??t1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function gy(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 UD(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await gy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await gy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const $D=["image/webp","image/jpeg"];function i1(e){return $D.includes(e.type)&&e.size<=zp}async function FD(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 Vu(e){if(i1(e))return e;const t=await FD(e);return UD(t)}function qD(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 WD(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(qD):[]}async function GD(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 YD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function VD(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 XD({image:e,authFetch:t}){const i=YD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function ZD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const N=await WD(e);E||o(N)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),j=async E=>{h(null),f(E.token);try{const N=await GD(e,E);await i(N)}catch(N){h(N instanceof Error?N.message:"Could not import the generated image")}finally{f(null)}},D=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),D&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),D&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),D&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(XD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[VD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>j(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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const QD={done:"✓",current:"▸",todo:"○"};function JD({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=XS(t),f=((E=e.steps.find(N=>N.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(N=>N.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",j=v.filter(N=>N.status!=="done").length,D=p.reduce((N,I)=>N+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[j===0?"Progress details":`${j} step${j===1?"":"s"} left`,D>0?` · ${D} blocker${D===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(N=>d.jsxs("li",{"data-testid":`finish-step-${N.key}`,"data-status":N.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${N.status==="current"?"border-accent/40 bg-accent/10 text-accent":N.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:QD[N.status]}),d.jsx("span",{children:N.label}),N.detail&&d.jsxs("span",{className:"text-muted",children:["· ",N.detail]})]},N.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(N=>d.jsxs("div",{"data-testid":`finish-issue-group-${N.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:N.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:N.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},N.key))})]})]})]})}function eM(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 Do(e){return(!!e.cleanImagePath||fn(e))&&wm(e).length>0}function xy(e){const t=new Date().toISOString();return{status:"generated",baseSig:ul(e),generatedAt:t,updatedAt:t}}function n1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":fn(e)?"text":"missing"}const _y={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},tM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function iM(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"}:fn(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 nM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Do(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:fn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function rM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:j,repairing:D,conversionPng:E,onConvert:N,converting:I,rowRef:te}){var He,ke;const q=w.useRef(null),[R,ie]=w.useState(!1),[fe,be]=w.useState(null),[B,ne]=w.useState(!1),[F,G]=w.useState(!1),[Y,U]=w.useState(!1),[A,z]=w.useState(!1),$=n1(e),ge=S.length>0,T=!!E,M=w.useCallback(async()=>{E&&(z(!0),await N(e.id,E),z(!1),h())},[E,N,e.id,h]),V=w.useCallback(async Ue=>{ie(!0),be(null);try{let Je=Ue;if(!i1(Ue))try{Je=await Vu(Ue)}catch(ze){return be(ze instanceof Error?ze.message:"Could not import image"),!1}const at=Je.type==="image/jpeg"?"jpg":"webp",Ve=new FormData;Ve.append("file",new File([Je],`clean.${at}`,{type:Je.type}));const Et=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ve});if(!Et.ok){const ze=await Et.json();return be(ze.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{ie(!1)}},[c,t,i,e.id,h]),C=iM(e,T,ge),X=e.cleanImagePath??E??null,se=((He=e.overlays)==null?void 0:He.length)??0,le=!fn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!ge&&!T,K=!ge&&!T&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Do(e),he=(((ke=e.overlays)==null?void 0:ke.length)??0)>0?"Re-draft with AI":"AI draft lettering",_e=C.key==="convert"?{label:A?"Converting…":"Convert image",onClick:M,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=nM(e),Le=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||fn(e);return d.jsxs("div",{ref:te,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${tM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${_y[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),X||fn(e)?d.jsx(ND,{storyName:t,assetPath:X,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Le?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:fn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${_y[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[le?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:se>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):_e?d.jsx("button",{onClick:_e.onClick,disabled:C.key==="convert"&&(A||I),"data-testid":_e.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:_e.label}):null,!le&&!_e&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[T&&d.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:[d.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."}),d.jsx("button",{onClick:M,disabled:A||I,"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:A?"Converting…":"Convert image"})]}),ge&&!T&&d.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:[S.map((Ue,Je)=>d.jsx("p",{className:"text-[11px] text-error",children:Ue},Je)),d.jsx("button",{onClick:j,disabled:D,"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:D?"Repairing…":"Clear stale path"})]}),!fn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(my(e,i)),ne(!0),setTimeout(()=>ne(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ue=>{var at;const Je=(at=Ue.target.files)==null?void 0:at[0];Je&&V(Je),Ue.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var Ue;return(Ue=q.current)==null?void 0:Ue.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(Ue=>!Ue),disabled:R,"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:Y?"Hide Codex images":"Import from Codex"})]}),Y&&d.jsx(ZD,{authFetch:c,cutId:e.id,onImport:async Ue=>{await V(Ue)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.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."}),$==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(my(e,i)),G(!0),setTimeout(()=>G(!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:F?"Copied!":"Copy Codex task"})]}),$==="missing"&&f&&d.jsx("button",{onClick:_,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"}),fe&&d.jsx("p",{className:"text-xs text-error mt-1",children:fe})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||fn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ue,Je)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[Ue.speaker,":"]})," ",Ue.text]},Je))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function by({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var pr,Lt,oe;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[j,D]=w.useState(!0),[E,N]=w.useState(null),[I,te]=w.useState(null),[q,R]=w.useState(null),[ie,fe]=w.useState(!1),[be,B]=w.useState([]),[ne,F]=w.useState(!1),[G,Y]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[M,V]=w.useState(!1),[C,X]=w.useState(null),[se,le]=w.useState(null),[K,he]=w.useState(null),[_e,Me]=w.useState(!1),[Le,He]=w.useState(new Set),[ke,Ue]=w.useState(new Map),[Je,at]=w.useState(!1),[Ve,Et]=w.useState(null),[ze,_t]=w.useState(!1),[Te,Kt]=w.useState(null),mi=w.useRef(new Map),wt=w.useRef(null),et=t.replace(/\.md$/,"");w.useEffect(()=>{var O;c&&wt.current!==c.seq&&(wt.current=c.seq,c.openEditor?R(c.cutId):(te(c.cutId),Kt(c.cutId)),(O=S.current)==null||O.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ce;if(Te==null)return;const O=mi.current.get(Te);O&&((ce=O.scrollIntoView)==null||ce.call(O,{behavior:"smooth",block:"center"}),Kt(null))},[Te,x]);const Q=w.useCallback(async()=>{var O;try{const ce=await i(`/api/stories/${e}/cuts/${et}`);if(ce.status===404){b(null);return}if(!ce.ok){const De=await ce.json();N(De.error||"Failed to load cuts");return}const Ee=await ce.json();b(Ee),N(null);try{const De=await i(`/api/stories/${e}/${t}`);if(De.ok){const Ne=await De.json(),Pe=typeof(Ne==null?void 0:Ne.content)=="string"?Ne.content:"",We=Array.isArray(Ee==null?void 0:Ee.cuts)?Ee.cuts:[],rt=Pe.length>0&&KS(Pe,We).ready,Xe=(Ne==null?void 0:Ne.status)==="published"||(Ne==null?void 0:Ne.status)==="published-not-indexed";A({markdownReady:rt,published:Xe})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(O=v.current)==null||O.call(v)}catch{N("Failed to load cuts")}finally{D(!1)}},[i,e,et,t]),xe=w.useCallback(async O=>!!(await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok,[i,e,et]),je=w.useCallback(async()=>{at(!1);try{const O=await i(`/api/stories/${e}/cuts/${et}/detect-clean-images`);if(!O.ok)return;const ce=await O.json();He(new Set(Array.isArray(ce.detected)?ce.detected:[]));const Ee=new Map,De=ce.stale;if(Array.isArray(De))for(const Ne of De){if(typeof(Ne==null?void 0:Ne.cutId)!="number"||typeof(Ne==null?void 0:Ne.message)!="string")continue;const Pe=Ee.get(Ne.cutId)??[];Pe.push(Ne.message),Ee.set(Ne.cutId,Pe)}Ue(Ee),at(!0)}catch{}},[i,e,et]),$e=w.useCallback(async()=>{Et(null);try{const O=await i(`/api/stories/${e}/cuts/${et}/asset-diagnostics`);if(!O.ok)return;const ce=await O.json();Et(Array.isArray(ce.diagnostics)?ce.diagnostics:null)}catch{}},[i,e,et]),nt=w.useCallback(async()=>{_t(!0);try{await Promise.all([Q(),je(),$e()])}finally{_t(!1)}},[Q,je,$e]),Wt=w.useCallback(async(O,ce={})=>{var Ne;if(!x)return!1;const Ee=x.cuts.find(Pe=>Pe.id===O);if(!Ee||!Do(Ee)||(((Ne=Ee.overlays)==null?void 0:Ne.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const De=uy(Ee);if(De.length===0)return le(`Cut ${Ee.id}: no script lines available to draft.`),!1;he(O),le(null);try{const Pe={...x,cuts:x.cuts.map(rt=>rt.id===O?{...rt,overlays:De,aiDraft:xy(De)}:rt)};return await xe(Pe)?(le(`Cut ${Ee.id}: AI draft ready`),await Q(),ce.openEditor&&R(O),!0):(le(`Cut ${Ee.id}: AI draft failed`),!1)}finally{he(null)}},[x,xe,Q]),ui=w.useCallback(async()=>{if(!x)return;const O=x.cuts.filter(ce=>{var Ee;return Do(ce)&&(((Ee=ce.overlays)==null?void 0:Ee.length)??0)===0&&!ce.finalImagePath&&!ce.uploadedCid&&!ce.uploadedUrl});if(O.length===0){le("No unlettered cuts need an AI draft");return}Me(!0),le(null);try{const ce={...x,cuts:x.cuts.map(De=>{if(!O.some(Pe=>Pe.id===De.id))return De;const Ne=uy(De);return Ne.length>0?{...De,overlays:Ne,aiDraft:xy(Ne)}:De})};if(!await xe(ce)){le("AI draft failed");return}le(`AI draft ready for ${O.length} cut${O.length===1?"":"s"}`),await Q()}finally{Me(!1)}},[x,xe,Q]),Bt=w.useCallback(async()=>{$(!0),le(null),B([]);try{const O=await i(`/api/stories/${e}/cuts/${et}/sync-clean-images`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Sync failed");else{const Ee=Array.isArray(ce.synced)?ce.synced.length:0,De=Array.isArray(ce.cleared)?ce.cleared.length:0,Ne=Array.isArray(ce.rejected)?ce.rejected:[];Ne.length>0&&B(Ne.map(We=>`Cut ${We.cutId}: ${We.reason}`));const Pe=[];Ee>0&&Pe.push(`Synced ${Ee}`),De>0&&Pe.push(`Cleared ${De} stale path${De===1?"":"s"}`),le(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await je(),await $e()}}catch{le("Sync failed")}$(!1)},[i,e,et,Q,je,$e]),yt=w.useCallback(async(O,ce)=>{try{const Ee=await i(IS(e,ce));if(!Ee.ok)return!1;const De=await Ee.blob(),Ne=await Vu(new File([De],"clean.png",{type:De.type||"image/png"})),Pe=Ne.type==="image/jpeg"?"jpg":"webp",We=new FormData;return We.append("file",new File([Ne],`clean.${Pe}`,{type:Ne.type})),(await i(`/api/stories/${e}/cuts/${et}/upload-clean/${O}`,{method:"POST",body:We})).ok}catch{return!1}},[i,e,et]),Rt=w.useCallback(async O=>{V(!0),X(null);let ce=0;const Ee=[];for(const De of O)await yt(De.cutId,De.pngPath)?ce++:Ee.push(De.cutId);await nt(),V(!1),X(Ee.length===0?`Converted ${ce} image${ce===1?"":"s"} to WebP`:`Converted ${ce}; ${Ee.length} failed (Cut ${Ee.join(", ")}) — try Convert image on each`)},[yt,nt]),Qe=w.useCallback(async()=>{var Ne;if(!x)return;F(!0),Y(""),B([]);const O=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),ce=[],Ee=HD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>Y(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Jt.ok){const{cid:$n,url:gr}=await Jt.json();return{ok:!0,status:Jt.status,cid:$n,url:gr}}const qi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:qi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:qi,waitMs:$n})=>Y(`Cut ${We.id} rate-limited — waiting ${Math.round($n/1e3)}s before retry ${Jt}/${qi}...`)});if(!Gt.ok){ce.push(`Cut ${We.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Dt,url:ki}=Gt;(await i(`/api/stories/${e}/cuts/${et}/set-uploaded/${We.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Dt,url:ki})})).ok||ce.push(`Cut ${We.id}: failed to record upload`)}catch(rt){ce.push(`Cut ${We.id}: ${rt instanceof Error?rt.message:"failed"}`)}}if(ce.length>0){B(ce),F(!1),Y(""),Q();return}Y("Preparing episode for publishing…");const De=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(De.ok){const Pe=await De.json();((Ne=Pe.warnings)==null?void 0:Ne.length)>0&&B(Pe.warnings)}F(!1),Y(""),Q()},[x,i,e,et,a,Q]),hi=w.useCallback(async()=>{T(!0),le(null);try{const O=await i(`/api/stories/${e}/cuts/${et}/repair-asset-paths`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Repair failed");else{const Ee=Array.isArray(ce.cleared)?ce.cleared.length:0;le(Ee>0?`Cleared ${Ee} stale path${Ee===1?"":"s"}`:"No stale paths to clear"),await Q(),await je()}}catch{le("Repair failed")}T(!1)},[i,e,et,Q,je]),[H,Se]=w.useState(!1),Oe=w.useCallback(async(O,ce=!0)=>{if(x){Se(!0);try{const Ee=x.cuts.reduce((rt,Xe)=>Math.max(rt,Xe.id),0)+1,De={id:Ee,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"},Ne=[...x.cuts];Ne.splice(Math.max(0,Math.min(O,Ne.length)),0,De);const Pe={...x,cuts:Ne},We=await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(We.ok)ce?R(Ee):te(Ee),await Q();else{const rt=await We.json().catch(()=>({}));le(rt.error||"Could not add text panel")}}catch{le("Could not add text panel")}Se(!1)}},[x,i,e,et,Q]),Ae=w.useCallback(()=>Oe((x==null?void 0:x.cuts.length)??0,!0),[Oe,x]);if(w.useEffect(()=>{Q(),je(),$e()},[Q,je,$e]),j)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[et,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(O=>O.id===q):null;if(Ge)return d.jsx(ED,{storyName:e,cut:Ge,plotFile:et,language:s,authFetch:i,targetLabel:fn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(O,ce)=>{const Ee={...x,cuts:x.cuts.map(Ne=>Ne.id===q?{...Ne,overlays:O,aiDraft:ce??Ne.aiDraft??null}:Ne)};if(!await xe(Ee))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{R(null),Q()}});const Fe=x.cuts.reduce((O,ce)=>{const Ee=n1(ce);return O[Ee]++,O},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(O=>!fn(O)).length,ft=x.cuts.filter(O=>WS(O)).map(O=>O.id),ct=cD({cuts:x.cuts,published:U.published}),Vt=((pr=ct.steps.find(O=>O.key==="upload"))==null?void 0:pr.status)==="done",Ci=x.cuts.some(O=>O.finalImagePath&&!O.uploadedCid)||Vt&&!U.markdownReady,pt=(Ve??[]).filter(O=>O.state==="needs-conversion"&&O.convertiblePng).map(O=>({cutId:O.cutId,pngPath:O.convertiblePng})),Fi=new Map(pt.map(O=>[O.cutId,O.pngPath])),Nn=(Ve??[]).filter(O=>O.state==="needs-conversion"&&O.issue).map(O=>O.issue),ln=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Lt=et.match(/\d+/))==null?void 0:Lt[0])??"0",10)+1}`,Un=typeof x.title=="string"?x.title:null,on=x.cuts.filter(O=>!fn(O)),xn={cuts:x.cuts.length,artwork:on.filter(O=>O.cleanImagePath||Fi.has(O.id)).length,converted:on.filter(O=>O.cleanImagePath&&/\.(webp|jpe?g)$/i.test(O.cleanImagePath)).length,lettered:x.cuts.filter(O=>{var ce;return(((ce=O.overlays)==null?void 0:ce.length)??0)>0||!!O.finalImagePath}).length,uploaded:x.cuts.filter(O=>O.uploadedCid||O.uploadedUrl).length},cn=x.cuts.filter(O=>{var ce;return Do(O)&&(((ce=O.overlays)==null?void 0:ce.length)??0)===0&&!O.finalImagePath&&!O.uploadedCid&&!O.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:ln}),Un&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Un]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[xn.cuts," cuts · ",xn.artwork," artwork found ·"," ",xn.converted," converted · ",xn.lettered," ","lettered · ",xn.uploaded," uploaded"]})]}),cn>0&&d.jsx("button",{onClick:ui,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${cn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Fe.missing>0&&d.jsxs("span",{className:"text-muted",children:[Fe.missing," missing"]}),Fe.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.clean," clean"]}),Fe.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Fe.lettered," lettered"]}),Fe.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.uploaded," uploaded"]}),Fe.text>0&&d.jsxs("span",{className:"text-accent",children:[Fe.text," text ",Fe.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),B([]);try{const O=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(O.ok){const ce=await O.json();B(ce.warnings||[])}}catch{}fe(!1)},disabled:ie,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:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:H,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:H?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:nt,disabled:ze,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:ze?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Bt,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"}),d.jsx("button",{onClick:Qe,disabled:ne||!(x!=null&&x.cuts.some(O=>O.finalImagePath&&!O.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),ft.length>0&&d.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:[ft.length===1?"Cut":"Cuts"," ",ft.join(", ")," ",ft.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",ft.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),Je&&dt>0&&Fe.missing===0&&ke.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),se&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:se}),pt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[pt.length," PNG image",pt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Rt(pt),disabled:M,"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:M?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),Nn.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Nn.map((O,ce)=>d.jsx("li",{children:O},ce))})]})]}),Ve&&Ve.length>0&&(()=>{const O=eM(Ve),ce=Ve.filter(Ee=>Ee.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",O.uploaded," uploaded · ",O.finalReady," final ·"," ",O.cleanReady," clean · ",O.planned," planned",O.needsConversion>0?` · ${O.needsConversion} needs conversion`:"",O.missing>0?` · ${O.missing} missing`:""]}),ce.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ce.map(Ee=>d.jsx("li",{children:Ee.issue},Ee.cutId))})]})})(),d.jsx(JD,{checklist:ct,issues:be,onFinish:Qe,finishing:ne,progressText:G,canFinish:Ci,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((O,ce)=>{var Ee;return d.jsxs(w.Fragment,{children:[d.jsx(vy,{index:ce,beforeLabel:ce===0?"Episode opening":`After cut ${(Ee=x.cuts[ce-1])==null?void 0:Ee.id}`,afterLabel:`Before cut ${O.id}`,disabled:H,onAdd:()=>Oe(ce)}),d.jsx(rM,{cut:O,storyName:e,plotFile:et,language:s,expanded:I===O.id,onToggle:()=>te(I===O.id?null:O.id),authFetch:i,onUpdated:()=>{Q(),je(),$e()},onOpenEditor:()=>R(O.id),detectedLocalClean:Le.has(O.id),onSyncClean:Bt,syncing:z,onAiDraft:()=>{Wt(O.id,{openEditor:!0})},aiDrafting:K===O.id,staleMessages:ke.get(O.id)??[],onRepairStale:hi,repairing:ge,conversionPng:Fi.get(O.id)??null,onConvert:yt,converting:M,rowRef:De=>{De?mi.current.set(O.id,De):mi.current.delete(O.id)}})]},O.id)}),d.jsx(vy,{index:x.cuts.length,beforeLabel:`After cut ${(oe=x.cuts[x.cuts.length-1])==null?void 0:oe.id}`,afterLabel:"Episode ending",disabled:H,onAdd:()=>Oe(x.cuts.length)})]})]})}function vy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}function Cm({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?d.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:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.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}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),c&&d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:"Prompt copied."})]}),e.actionKind==="agent"&&e.prompt?d.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?d.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?d.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:d.jsxs("div",{className:"flex items-start gap-3",children:[d.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"}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No next action available"}),d.jsx("p",{className:"mt-0.5 text-xs text-muted",children:"This workflow has no queued next step right now."})]})]})}):null}function sM({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]),[f,_]=w.useState(null);return f!==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]),d.jsx(Cm,{coach:c,onAction:a,showEmptyState:o})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 yy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Io(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 dM(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 Ip(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 km(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Em(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function Sy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...gl,attributes:{...gl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:j=!1,onFocusedLetteringModeChange:D,onFocusedLetteringWorkspaceVisibleChange:E}){const[N,I]=w.useState(null),[te,q]=w.useState(!1),[R,ie]=w.useState("preview"),[fe,be]=w.useState("publish"),[B,ne]=w.useState("text"),[F,G]=w.useState(null),Y=w.useCallback((re,ye)=>{ie("edit"),G(Ce=>({cutId:re,openEditor:ye,seq:((Ce==null?void 0:Ce.seq)??0)+1}))},[]),[U,A]=w.useState(""),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[M,V]=w.useState(!1),[C,X]=w.useState(null),[se,le]=w.useState(""),[K,he]=w.useState(""),[_e,Me]=w.useState(!1),[Le,He]=w.useState(null),[ke,Ue]=w.useState(0),[Je,at]=w.useState(0),[Ve,Et]=w.useState(null),[ze,_t]=w.useState(null),[Te,Kt]=w.useState(null),[mi,wt]=w.useState(0),et=w.useRef(null),Q=w.useRef(!1),[xe,je]=w.useState(!1),[$e,nt]=w.useState(dl[0]),[Wt,ui]=w.useState(ts[0]),[Bt,yt]=w.useState(!1),[Rt,Qe]=w.useState(null),[hi,H]=w.useState(null),[Se,Oe]=w.useState(!1),[Ae,Ge]=w.useState(!1),[Fe,dt]=w.useState(!1),[ft,ct]=w.useState(null),[Vt,Ci]=w.useState(!1),pt=w.useRef(null),Fi=w.useRef(null),[Nn,ln]=w.useState(!1),[Un,on]=w.useState(null),[xn,cn]=w.useState(null),[pr,Lt]=w.useState("unknown"),oe=w.useRef(!1),[O,ce]=w.useState(!1),[Ee,De]=w.useState(!1),[Ne,Pe]=w.useState(null),[We,rt]=w.useState([]),[Xe,Nt]=w.useState(null),jt=w.useRef(null),Gt=w.useRef(null),Dt=w.useCallback(async()=>{if(!e||!t){I(null);return}const re=`${e}/${t}`,ye=Gt.current!==re;ye&&(Gt.current=re);try{const Ce=await i(`/api/stories/${e}/${t}`);if(Ce.ok){const tt=await Ce.json();I(tt),(ye||!Q.current)&&(A(tt.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{q(!0),Dt().finally(()=>q(!1))},[Dt]),w.useEffect(()=>{if(!e||!t||R==="edit"&&ge)return;const re=setInterval(Dt,3e3);return()=>clearInterval(re)},[e,t,Dt,R,ge]);const[ki,mr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){mr(null);return}let re=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||mr(ye?Op(ye.cuts||[]):null)}).catch(()=>{re||mr(null)}),()=>{re=!0}},[Jt,e,i]);const qi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qi||!e||!t){He(null),Ue(0),at(0),Et(null);return}let re=!1;const ye=t.replace(/\.md$/,"");return Et(null),(async()=>{try{const[Ce,tt]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(re)return;if(!tt.ok){He("error"),Ue(0),at(0),Et(null);return}const Pt=await tt.json(),Ni=Pt.cuts||[],Gn=Ce.ok?(await Ce.json()).content??"":"",or=VS(Gn,Ni);re||(He(or.stage),Ue(or.awaitingCount),at(or.totalCuts),Et(Op(Ni)),Kt(typeof Pt.title=="string"?Pt.title:null))}catch{re||(He("error"),Ue(0),at(0),Et(null))}})(),()=>{re=!0}},[qi,e,t,i,N==null?void 0:N.content,N==null?void 0:N.status,mi]),w.useEffect(()=>{if(!e){_t(null);return}let re=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||_t((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{re=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const re=Cu(p);let ye=re??"";if(!re&&ze){const tt=ze.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);tt&&(ye=Cu(tt[1].replace(/\*+/g,"").trim())??"")}le(ye);let Ce=h&&ts.find(tt=>tt.toLowerCase()===h.toLowerCase())||"";if(!Ce&&ze){const tt=ze.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);tt&&(Ce=ts.find(Pt=>Pt.toLowerCase()===tt[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(Ce),Me(f??!1)},[e,p,h,f,ze]);const $n=w.useCallback(re=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]),ei=w.useCallback(async()=>{if(!e||!t)return;const re=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${re}/generate-markdown`,{method:"POST"})).ok&&(await Dt(),wt(Ce=>Ce+1))}catch{}},[e,t,i,Dt]),Br=w.useCallback((re,ye)=>{if(re==="view-progress"){x==null||x();return}if(ye&&ye!==t){b==null||b(ye);return}switch(re){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ie("edit"),ne("cuts");break;case"generate-markdown":ei();break;case"publish":ie("preview");break}},[t,x,b,ei]),Fn=w.useCallback(re=>{var tt;const ye=(tt=re.target.files)==null?void 0:tt[0];if(!ye)return;oe.current=!0,on(null),cn(null);const Ce=yy(ye);if(Ce){Qe(null),H(Pt=>(Pt&&URL.revokeObjectURL(Pt),null)),pt.current&&(pt.current.value=""),ct(Ce),Lt("invalid");return}Qe(ye),H(Pt=>(Pt&&URL.revokeObjectURL(Pt),URL.createObjectURL(ye))),ct(null),Lt("selected")},[]),ar=w.useCallback(async re=>{var Ce;const ye=(Ce=re.target.files)==null?void 0:Ce[0];if(Fi.current&&(Fi.current.value=""),!(!ye||!e)){oe.current=!0,on(null),ln(!0),ct(null);try{let tt;try{tt=await Vu(ye)}catch(vr){Qe(null),H(Yi=>(Yi&&URL.revokeObjectURL(Yi),null)),ct(vr instanceof Error?vr.message:"Could not import image");return}const Pt=tt.type==="image/jpeg"?"jpg":"webp",Ni=new File([tt],`cover.${Pt}`,{type:tt.type}),Gn=new FormData;Gn.append("file",Ni);const or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Gn});if(!or.ok){const vr=await or.json().catch(()=>({}));ct(vr.error||"Cover import failed");return}Qe(Ni),H(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(Ni))),cn(null),Lt("selected"),ct(null)}catch{ct("Cover import failed")}finally{ln(!1)}}},[e,i]),Wi=w.useCallback(async re=>{if(re.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(re.type)){Pe("Only WebP and JPEG images are accepted");return}De(!0),Pe(null);try{const Ce=new FormData;Ce.append("file",re);const tt=await i("/api/publish/upload-plot-image",{method:"POST",body:Ce});if(!tt.ok){const Ni=await tt.json();throw new Error(Ni.error||"Upload failed")}const Pt=await tt.json();rt(Ni=>[...Ni,{cid:Pt.cid,url:Pt.url}])}catch(Ce){Pe(Ce instanceof Error?Ce.message:"Upload failed")}finally{De(!1),jt.current&&(jt.current.value="")}},[i]),Ct=w.useCallback(re=>{var Ce;const ye=(Ce=re.target.files)==null?void 0:Ce[0];ye&&Wi(ye)},[Wi]),qn=w.useCallback(async()=>{if(N!=null&&N.storylineId){Oe(!0),ct(null),Ci(!1);try{let re;if(Rt){const Ce=new FormData;Ce.append("file",Rt);const tt=await i("/api/publish/upload-cover",{method:"POST",body:Ce});if(!tt.ok){const Ni=await tt.json();throw new Error(Ni.error||"Cover upload failed")}re=(await tt.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:N.storylineId,...re!==void 0&&{coverCid:re},genre:$e,language:Wt,isNsfw:Bt})});if(!ye.ok){const Ce=await ye.json();throw new Error(Ce.error||"Update failed")}Ci(!0),Qe(null),re!==void 0&&(dt(!0),H(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),Lt("unknown"),pt.current&&(pt.current.value="")),setTimeout(()=>Ci(!1),3e3)}catch(re){ct(re instanceof Error?re.message:"Update failed")}finally{Oe(!1)}}},[N==null?void 0:N.storylineId,Rt,$e,Wt,Bt,i]);w.useEffect(()=>{je(!1),Qe(null),H(null),ct(null),Ci(!1),Ge(!1),ce(!1),rt([]),Pe(null),on(null),cn(null),Lt("unknown"),oe.current=!1,ne("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!N||N.storylineId||N.status==="published"||N.status==="published-not-indexed"||oe.current)return;let re=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(re||!ye.ok)return;const Ce=await ye.json();if(re)return;if(!(Ce!=null&&Ce.found)){Lt("none");return}if(!Ce.valid){cn(Ce.error||"Detected cover asset is invalid and was not used"),Lt("invalid");return}const tt=await i(`/api/stories/${e}/asset/${Ce.path.replace(/^assets\//,"")}`);if(re||!tt.ok)return;const Pt=await tt.blob(),Ni=new File([Pt],Ce.path.split("/").pop()||"cover.webp",{type:Ce.type});if(yy(Ni)||re||oe.current)return;Qe(Ni),H(Gn=>(Gn&&URL.revokeObjectURL(Gn),URL.createObjectURL(Ni))),on(Ce.path),Lt("detected")}catch{}})(),()=>{re=!0}},[e,t,N,N==null?void 0:N.status,N==null?void 0:N.storylineId,i]),w.useEffect(()=>{if(!xe||!(N!=null&&N.storylineId))return;Ge(!1);const re="https://plotlink.xyz";let ye=!1;return fetch(`${re}/api/storyline/${N.storylineId}`).then(Ce=>Ce.ok?Ce.json():null).then(Ce=>{if(!ye){if(!Ce){ct("Could not load current story metadata");return}if(Ce.genre){const tt=Cu(Ce.genre);tt&&nt(tt)}if(Ce.language){const tt=ts.find(Pt=>Pt.toLowerCase()===Ce.language.toLowerCase());tt&&ui(tt)}Ce.isNsfw!==void 0&&yt(!!Ce.isNsfw),dt(!!(Ce.coverCid||Ce.coverUrl||Ce.cover)),Ge(!0)}}).catch(()=>{ye||ct("Could not load current story metadata")}),()=>{ye=!0}},[xe,N==null?void 0:N.storylineId]),w.useEffect(()=>{if(R!=="edit")return;const re=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),gr())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[R,gr]),w.useEffect(()=>{if((N==null?void 0:N.status)!=="published-not-indexed"||!N.publishedAt)return;const re=new Date(N.publishedAt).getTime(),ye=300*1e3,Ce=()=>{const Pt=Math.max(0,ye-(Date.now()-re));X(Pt)};Ce();const tt=setInterval(Ce,1e3);return()=>clearInterval(tt)},[N==null?void 0:N.status,N==null?void 0:N.publishedAt]);const ya=C!==null&&C<=0,Lr=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!N)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const xr=(R==="edit"?U:(N==null?void 0:N.content)??"").length,Ei=t==="genesis.md",gi=t?/^plot-\d+\.md$/.test(t):!1,Gi=c==="cartoon"&&gi,jn=c==="cartoon"&&Ei,Or=jn||Gi,Tn=(N==null?void 0:N.status)==="published"||(N==null?void 0:N.status)==="published-not-indexed",Sa=S&&Or,yl=jn?ki?ki.total:null:Gi?Le===null?null:Je:null,_r=hD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Tn,cutCount:yl,cutProgress:jn?ki:null}),Ko=(jn||Gi)&&!Tn,as=Ko?Em({fileName:t,fileContent:(N==null?void 0:N.content)??"",storySlug:e??"",structureContent:ze,contentType:"cartoon",episodeTitle:Te}):null,wa=!!as&&Io(as,t),Ca=Gi&&!Tn&&!km({fileContent:(N==null?void 0:N.content)??"",episodeTitle:Te}),qs=jn&&!Tn?ym((N==null?void 0:N.content)??""):null,Vo=!!qs&&qs.blockers.length>0,ka="w-full max-w-[32rem] rounded-xl border px-3 py-3",lr={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ea=re=>{if(!jn)return null;const ye=cM({hasSelectedCover:!!Rt,invalid:pr==="invalid",attached:re});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${lr[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},Ws=wa||Ca,ls=()=>{if(!Ko||!as)return null;const re=Ei?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":wa?"true":"false","data-blocked":Ws?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[re,":"]})," ",d.jsx("span",{className:Ws?"text-error font-medium":"text-foreground",children:as})]}),wa?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Ei?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ca?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",as,"” 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]})},os=()=>qs?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Vo?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),qs.blockers.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:re},`b-${ye}`)),qs.warnings.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:re},`w-${ye}`))]}):null,cs=Ei||gi?1e4:null,us=!Tn&&cs!==null&&xr>cs,Xo=(N==null?void 0:N.content)??"",br=Tn?{count:0,warnings:[]}:yM(Xo),Wn=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:et,value:U,onChange:re=>{A(re.target.value),T(!0),Q.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:ge?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!ge||z,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Sa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(N==null?void 0:N.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(N==null?void 0:N.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:N.indexError,children:"Published (not indexed)"}),(N==null?void 0:N.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${us?"text-error font-medium":"text-muted"}`,children:[xr.toLocaleString(),cs!==null?`/${cs.toLocaleString()}`:" chars"]}),us&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(xr-cs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",ge&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),!Sa&&c==="cartoon"&&e&&t&&d.jsx(sM,{storyName:e,fileName:t,authFetch:i,refreshKey:mi,onAction:Br,showEmptyState:!0}),R==="preview"?Gi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>be("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>be("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(mD,{content:(N==null?void 0:N.content)??"",stage:Le}):d.jsx(Q3,{storyName:e,fileName:t,authFetch:i,onEditCut:Y})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:N!=null&&N.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(lS,{remarkPlugins:[cS,MS],rehypePlugins:[[zS,_M]],children:N.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Gi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(by,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:D,workspaceVisible:j,onWorkspaceVisibleChange:E})}):jn?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>ne("text"),className:`px-2 py-0.5 text-[11px] rounded ${B==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ne("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${B==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="cuts"?d.jsx(by,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:D,workspaceVisible:j,onWorkspaceVisibleChange:E}):Wn})]}):Wn,!Sa&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:_r}):(N==null?void 0:N.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ya&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!N.txHash)){V(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:N.txHash,content:N.content,storylineId:N.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:N.txHash,storylineId:N.storylineId,contentCid:"",gasCost:""})}),Dt())}catch{}V(!1)}},disabled:M,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:M?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),gi&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`,...o.current()});return/^[\t ]/.test(f)&&(f=Oo(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function gm(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 wR(e){const t=gm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):gm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Fu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Du(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Du(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Rf,tableHeader:Rf,tableRow:Rf}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Rf(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),j=f([E]);return j.slice(0,j.indexOf(` +`))}function p(v,S,N,M){const E=N.enter("tableCell"),j=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return j(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const j=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=pr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(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 qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Fo,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return kt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=ol(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Y=s.events[ne][1].type;if(Y==="lineEnding"||Y==="linePrefix")ne--;else break}const F=ne>-1?s.events[ne][1].type:null,G=F==="tableHead"||F==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):xt(B)?kt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,xt(B)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return xt(B)?kt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?te(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),j(B)):q(B)}function j(B){return B===45?(e.consume(B),j):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return xt(B)?kt(e,te,"whitespace")(B):te(B)}function te(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ie(B)}function ie(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ie):B===null||Ye(B)?(e.exit("tableRow"),t(B)):xt(B)?kt(e,ie,"whitespace")(B):(e.enter("data"),fe(B))}function fe(B){return B===null||B===124||qt(B)?(e.exit("data"),ie(B)):(e.consume(B),B===92?be:fe)}function be(B){return B===92||B===124?(e.consume(B),fe):fe(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,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 Qv(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 S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Ye(p)?t(p):xt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const la=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],cl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...la,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...la],h2:[["className","sr-only"]],img:[...la,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...la,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...la],table:[...la],ul:[...la,["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"]},Ls={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...cl,...t}:cl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Wo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Wo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Ls.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const sl=["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"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(sl.map(e=>[IS(e),e])),P3={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 yu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function _m(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=_m(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 Co(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,j=Math.max(1,_-E),I=a.fontWeight??400,te=iy((ie,fe)=>e(ie,fe,I),t,f,N),q=te.length*N*o,R=te.every(ie=>e(ie,N,I)<=f+.5);return{lines:te,ok:q<=j&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function jr(e,t,i){return Math.min(i,Math.max(t,e))}function al(e,t,i){return typeof e=="number"&&Number.isFinite(e)?jr(e,t,i):void 0}function bm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=al(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=al(t.lineHeightFactor,.9,2),c=al(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 Wu(e){if(!e||typeof e!="object")return;const t=e,i=al(t.paddingX,0,.25),s=al(t.paddingY,0,.25),a=al(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 ko(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=bm(e.textStyle),h=Wu(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 $S(e,t,i){const s=Wu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?jr(e,h,p):t+i/2,half:c}}function vm(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:j,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:j-I,y:E},base2:{x:j+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:vm(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Bp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 cu=.05;function $i(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?cu:jr(o?1-t-cu:(1-t)/2,0,1),_=c?cu:jr(h?1-i-cu:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=$i(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=$i(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if($i(t.x)&&$i(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=jr(c,0,1),h=jr(h,0,1),a=jr(a,.02,1),o=jr(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&$i(b.x)&&$i(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=bm(t.textStyle),x=Wu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&$i(t.x)&&$i(t.y)&&$i(t.width)&&$i(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=bm(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=Wu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return $i(e==null?void 0:e.x)&&$i(e==null?void 0:e.y)&&$i(e==null?void 0:e.width)&&$i(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function dn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||dn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function uu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(uu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(uu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(uu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(uu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function ym(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Df=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Df.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=[...Df.map(c=>c.key),"other"],a=c=>{var h;return((h=Df.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:aD(h)})}return o}const lD=220,Mf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function Sm(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)||Mf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Mf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Mf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Lp(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)dn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 _o(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Lp(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.total,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(j=>!_[j]),v=j=>s.needClean>0?_o(j,s.needClean):"no image cuts",S={plan:_o(s.total,s.total),clean:v(s.withClean),letter:_o(s.withText,s.total),export:_o(s.exported,s.total),upload:_o(s.uploaded,s.total),publish:null},N=x.map((j,I)=>({key:j,label:cD[j],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},wm=[{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:[]}],bD="system-ui, sans-serif",vD=wm.find(e=>e.family==="Noto Sans"),yD=wm.find(e=>e.category==="display");function QS(e){return wm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Mu(e){return`"${e.family}", ${bD}`}function SD(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 nl(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==nl(e.current)}function Cm(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=Cm(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Bp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function kn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const Su={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Bf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:Su[e.type]}const py=.05,ED=[{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 hu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,hi,Lt,yt,Dt,Qe,di;const b=QS(c),v=JS(),S=Mu(b),N=Mu(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let H=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Se}=await uy(async()=>{const{ensureFontsReady:Oe}=await import("./export-cut-BuLQ0Lx7.js");return{ensureFontsReady:Oe}},[]);await Se([b.family,v.family])}catch{}H||G(!0)})(),()=>{H=!0}},[b.family,v.family]);const M=_m(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),j=E.invalid.length,[I,te]=w.useState(!1),q=j===0&&E.changed&&E.overlays.length>0,[R,ie]=w.useState(()=>E.overlays),[fe,be]=w.useState(()=>nl(E.overlays)),B=w.useRef(null),ne=w.useCallback(H=>(Se,Oe,Ae=400)=>{var Fe;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Fe=B.current)==null?void 0:Fe.getContext("2d");return Ge?(Ge.font=`${Ae} ${Oe}px ${H}`,Ge.measureText(Se).width):Se.length*Oe*.5},[]),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(!1),[$,ge]=w.useState(!1),[T,D]=w.useState(null),[K,C]=w.useState(null),[X,re]=w.useState({x:0,y:0,width:0,height:0}),le=w.useRef(null),V=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const H=le.current;if(!H)return;const Se=H.clientWidth,Oe=H.clientHeight;let Ae,Ge;if(t.kind==="text"){const ct=YS(t.aspectRatio)??{width:800,height:600};Ae=ct.width,Ge=ct.height}else{const ct=V.current;if(!ct||!ct.naturalWidth)return;Ae=ct.naturalWidth,Ge=ct.naturalHeight}if(!Se||!Oe)return;const Fe=Math.min(Se/Ae,Oe/Ge),dt=Ae*Fe,ft=Ge*Fe;re({x:(Se-dt)/2,y:(Oe-ft)/2,width:dt,height:ft})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=le.current;if(!H)return;const Se=new ResizeObserver(()=>_e());return Se.observe(H),()=>Se.disconnect()},[_e]);const Me=w.useCallback(H=>{const Se=WS(H.type,H.x,H.y),Oe=Se.width,Ae=Math.max(.08,1-H.y);if(!H.text||!F||X.width<=0)return Se;const Ge=H.type==="sfx"?N:S,Fe=kn(Oe,X.width);let dt=H.type==="sfx"?.08:.12;for(let ft=0;ft<24;ft++){const ct=Math.min(dt,Ae),Kt=kn(ct,X.height);if(!Co(ne(Ge),H.text,Fe,Kt,ko({...H},X.height||300,Fe,Kt)).overflow||ct>=Ae)return{width:Oe,height:ct};dt+=.03}return{width:Oe,height:Math.min(dt,Ae)}},[F,X,ne,S,N]),Le=w.useCallback(H=>{const Se=Bp(H,.1+Math.random()*.3,.1+Math.random()*.3),Oe={...Se,...Me(Se)};ie(Ae=>[...Ae,Oe]),U(Oe.id)},[Me]),He=w.useCallback(H=>{const Oe={...Bp(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},Ae={...Oe,...Me(Oe)};ie(Ge=>[...Ge,Ae]),U(Ae.id)},[Me]),Ce=w.useCallback((H,Se)=>{ie(Oe=>Oe.map(Ae=>Ae.id===H?{...Ae,...Se}:Ae))},[]),Ue=w.useCallback(H=>{var dt;const Se=X.height||300,Oe=X.width>0?kn(H.width,X.width):200,Ae=X.height>0?kn(H.height,X.height):100,Ge=H.type==="sfx"?N:S,Fe=Co(ne(Ge),H.text,Oe,Ae,ko({...H,textStyle:void 0},Se,Oe,Ae));Ce(H.id,{textStyle:{mode:"manual",fontScale:Fe.fontSize/Math.max(1,Se),fontWeight:((dt=H.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Fe.fontSize>0?Fe.lineHeight/Fe.fontSize:1.2,speakerScale:Fe.fontSize>0&&Fe.speakerFontSize>0?Fe.speakerFontSize/Fe.fontSize:.8}})},[X,N,S,ne,Ce]),et=w.useCallback(H=>{ie(Se=>Se.filter(Oe=>Oe.id!==H)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),Ke=w.useCallback((H,Se)=>{H.stopPropagation(),U(Se),z(!1)},[]),Et=w.useCallback((H,Se,Oe)=>{H.stopPropagation(),H.preventDefault();const Ae=R.find(Ge=>Ge.id===Se);Ae&&(U(Se),he.current={id:Se,mode:Oe,startX:H.clientX,startY:H.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const H=Oe=>{const Ae=he.current;if(!Ae||X.width===0)return;const Ge=dy(Oe.clientX-Ae.startX,X.width),Fe=dy(Oe.clientY-Ae.startY,X.height);if(Ae.mode==="move"){const dt=hu(Ae.origX+Ge,0,1-Ae.origW),ft=hu(Ae.origY+Fe,0,1-Ae.origH);Ce(Ae.id,{x:dt,y:ft})}else{const dt=hu(Ae.origW+Ge,py,1-Ae.origX),ft=hu(Ae.origH+Fe,py,1-Ae.origY);Ce(Ae.id,{width:dt,height:ft})}},Se=()=>{he.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",Se),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",Se)}},[X,Ce]);const ze=w.useCallback(async()=>{var H;C(null);try{const Se=nl(R),Oe=((H=t.aiDraft)==null?void 0:H.status)==="generated"&&Se!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Oe??null),f&&a()}catch(Se){C(Se instanceof Error?Se.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),_t=w.useCallback(async()=>{if(j>0&&!I){const H=j;D(`${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}ge(!0),D(null);try{await s(R);const{exportCut:H,ensureFontsReady:Se}=await uy(async()=>{const{exportCut:pt,ensureFontsReady:qi}=await import("./export-cut-BuLQ0Lx7.js");return{exportCut:pt,ensureFontsReady:qi}},[]),Oe=R.some(pt=>pt.type==="sfx"),Ae=[b.family,...Oe?[v.family]:[]],{ready:Ge,missing:Fe}=await Se(Ae);if(!Ge){D(`Fonts not loaded: ${Fe.join(", ")}. Check your connection and retry.`),ge(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),ge(!1);return}const dt=M.url,ft=await H(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),ct=new FormData,Kt=ft.type==="image/webp"?"webp":"jpg";ct.append("file",ft,`cut-${t.id}.${Kt}`);const Ei=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:ct});if(Ei.ok)be(nl(R)),o==null||o();else{const pt=await Ei.json();D(pt.error||"Export failed")}}catch(H){D(H instanceof Error?H.message:"Export failed")}finally{ge(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,j,I]),Te=R.find(H=>H.id===Y),Vt=w.useMemo(()=>X3(R),[R]),ki=w.useRef(t.id);w.useEffect(()=>{ki.current!==t.id&&(ki.current=t.id,be(nl(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:R}),tt=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),Q=w.useMemo(()=>Cm(t),[t]),xe=w.useMemo(()=>{const H={};for(const Se of R){const Oe=F3(Se);let Ae=!1;if(F&&X.width>0&&Se.text){const Ge=Se.type==="sfx"?N:S,Fe=kn(Se.width,X.width),dt=kn(Se.height,X.height);Ae=Co(ne(Ge),Se.text,Fe,dt,ko(Se,X.height||300,Fe,dt)).overflow}(Oe||Ae)&&(H[Se.id]={outOfBounds:Oe,overflow:Ae})}return H},[R,F,X,ne,S,N]),je=Object.keys(xe).length,$e=t.kind==="text",nt=!t.cleanImagePath;return!$e&&nt&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),K&&d.jsx("span",{className:"text-[10px] text-error",children:K}),d.jsx("button",{onClick:_t,disabled:$,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:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{ze()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),j>0&&!I?d.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:[d.jsxs("span",{children:[j," overlay",j===1?"":"s"," ","from the cut plan ",j===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",j===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",j," unplaceable overlay",j===1?"":"s"]})]}):j>0?d.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 ",j," unplaceable overlay",j===1?"":"s"," — the export will not include"," ",j===1?"it":"them","."]}):q?d.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,Vt.length>0&&d.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,": ",Vt.length," bubble"," ",Vt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Vt.map(H=>`#${H.indexA+1} ${Bf(R[H.indexA])} ↔ #${H.indexB+1} ${Bf(R[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",tt.hasCleanImage],["script-text","Script text",tt.hasScriptText],["bubbles",`Bubbles placed${tt.bubblesPlaced?` (${tt.bubblesPlaced})`:""}`,tt.bubblesPlaced>0],["exported","Final exported",tt.exported],["uploaded","Uploaded",tt.uploaded]].map(([H,Se,Oe])=>d.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Oe?"true":"false",className:`flex items-center gap-1 ${Oe?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Oe?"✓":"○"}),Se]},H))}),Ct&&d.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."}),je>0&&d.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:[je," bubble",je===1?"":"s"," may not export cleanly:"," ",Object.entries(xe).map(([H,Se])=>{const Oe=R.findIndex(Ge=>Ge.id===H),Ae=[Se.outOfBounds?"outside image":null,Se.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Oe+1} ${Bf(R[Oe])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:le,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:V,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):$e?X.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:X.x,top:X.y,width:X.width,height:X.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&X.width===0){const Se=H.getBoundingClientRect();Se.width>0&&re({x:0,y:0,width:Se.width,height:Se.height})}},children:"Narration cut"}),X.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(H=>{if(H.type!=="speech")return null;const Se=X.x+kn(H.x,X.width),Oe=X.y+kn(H.y,X.height),Ae=kn(H.width,X.width),Ge=kn(H.height,X.height),Fe=$S(H,Ae,Ge),dt=H.tailAnchor?vm(Se,Oe,Ae,Ge,H.tailAnchor,Fe):null,ft=Math.max(1.5,X.height*.004),ct=H.id===Y;return d.jsx("path",{"data-testid":`balloon-${H.id}`,d:qS(Se,Oe,Ae,Ge,dt,Fe),className:`fill-white/95 ${ct?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:ct?ft+.5:ft,strokeLinejoin:"round"},H.id)})}),X.width>0&&R.map(H=>{const Se=X.x+kn(H.x,X.width),Oe=X.y+kn(H.y,X.height),Ae=kn(H.width,X.width),Ge=kn(H.height,X.height),Fe=H.id===Y,dt=H.type==="speech",ft=H.type==="narration",ct=!!xe[H.id];return d.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":ct?"true":"false",onClick:Kt=>Ke(Kt,H.id),onMouseDown:Kt=>Et(Kt,H.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[H.type]}`} ${ft?"bg-[#f4efe6]/85 rounded-md":""} ${Fe&&!dt?"ring-2 ring-accent":""} ${ct?"ring-2 ring-amber-500":""}`,style:{left:Se,top:Oe,width:Ae,height:Ge},children:[(()=>{var qi,jn;const Kt=H.type==="sfx"?N:S;if(!H.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Kt},children:Su[H.type]});const Ei=H.type!=="sfx"&&!!H.speaker;if(!F)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Kt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((qi=H.textStyle)==null?void 0:qi.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:Ei?`${H.speaker}: ${H.text}`:H.text});const pt=Co(ne(Kt),H.text,Ae,Ge,ko(H,X.height,Ae,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Kt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[Ei&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:pt.speakerFontSize,lineHeight:1.2},children:H.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:pt.fontSize,lineHeight:`${pt.lineHeight}px`,fontWeight:((jn=H.textStyle)==null?void 0:jn.fontWeight)??400},children:pt.lines.map((sn,Fn)=>d.jsx("span",{className:"block",children:sn},Fn))})]})})(),Fe&&d.jsx("div",{onMouseDown:Kt=>{Kt.stopPropagation(),Et(Kt,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)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((hi=t.aiDraft)==null?void 0:hi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(H=>d.jsxs("button",{onClick:()=>He(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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",Su[H.type]]})," ",d.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:Su[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:H=>Ce(Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:H=>Ce(Te.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"})]}),d.jsx("button",{onClick:()=>Ce(Te.id,Me(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Lt=Te.textStyle)==null?void 0:Lt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>Ce(Te.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"}):d.jsx("button",{type:"button",onClick:()=>Ue(Te),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"})]}),((yt=Te.textStyle)==null?void 0:yt.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:H=>Ce(Te.id,{textStyle:{...Te.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const H=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Se=>d.jsx("button",{type:"button",onClick:()=>Ce(Te.id,{tailAnchor:Se.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-${Se.key}`,children:Se.label},Se.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:Se=>Ce(Te.id,{tailAnchor:{...H,x:parseFloat(Se.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:Se=>Ce(Te.id,{tailAnchor:{...H,y:parseFloat(Se.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Dt=Te.bubbleStyle)==null?void 0:Dt.paddingX)??.06)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Qe=Te.bubbleStyle)==null?void 0:Qe.paddingY)??.08)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((di=Te.bubbleStyle)==null?void 0:di.cornerRadius)??.4)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?et(Te.id):z(!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:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Mu(x),S=Mu(b),N=_m(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[j,I]=w.useState(!1),[te,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,ie]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var ne;try{(ne=document.fonts)!=null&&ne.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const ne=new ResizeObserver(()=>{ie({width:B.clientWidth,height:B.clientHeight})});return ne.observe(B),()=>ne.disconnect()},[]);const fe=w.useCallback(B=>(ne,F,G=400)=>E?(E.font=`${G} ${F}px ${B}`,E.measureText(ne).width):ne.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${te.width} / ${te.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const ne=B.currentTarget.naturalWidth||te.width,F=B.currentTarget.naturalHeight||te.height;ne>0&&F>0&&q({width:ne,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=$S(B,G,Y),A=B.tailAnchor?vm(ne,F,G,Y,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(ne,F,G,Y,A,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var $;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=B.type==="sfx"?S:v,A=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${A?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:ne,top:F,width:G,height:Y},children:B.text?j?(()=>{var T;const ge=Co(fe(U),B.text,G,Y,ko(B,R.height,G,Y));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:ge.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ge.fontSize,lineHeight:`${ge.lineHeight}px`,fontWeight:((T=B.textStyle)==null?void 0:T.fontWeight)??400},children:ge.lines.map((D,K)=>d.jsx("span",{className:"block",children:D},K))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(Y*.05,14)),fontWeight:(($=B.textStyle)==null?void 0:$.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` +`).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(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(` +`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const Op=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Op)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=Op)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=Op}async function qD(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 Gu(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const j=await GD(e);E||o(j)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const j=await YD(e,E);await i(j)}catch(j){h(j instanceof Error?j.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(j=>j.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(j=>j.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(j=>j.status!=="done").length,M=p.reduce((j,I)=>j+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(j=>d.jsxs("li",{"data-testid":`finish-step-${j.key}`,"data-status":j.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${j.status==="current"?"border-accent/40 bg-accent/10 text-accent":j.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[j.status]}),d.jsx("span",{children:j.label}),j.detail&&d.jsxs("span",{className:"text-muted",children:["· ",j.detail]})]},j.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(j=>d.jsxs("div",{"data-testid":`finish-issue-group-${j.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:j.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:j.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},j.key))})]})]})]})}function tM(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 Ao(e){return(!!e.cleanImagePath||dn(e))&&Cm(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:nl(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":dn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:dn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Ao(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:dn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:j,converting:I,rowRef:te}){var He,Ce;const q=w.useRef(null),[R,ie]=w.useState(!1),[fe,be]=w.useState(null),[B,ne]=w.useState(!1),[F,G]=w.useState(!1),[Y,U]=w.useState(!1),[A,z]=w.useState(!1),$=r1(e),ge=S.length>0,T=!!E,D=w.useCallback(async()=>{E&&(z(!0),await j(e.id,E),z(!1),h())},[E,j,e.id,h]),K=w.useCallback(async Ue=>{ie(!0),be(null);try{let et=Ue;if(!n1(Ue))try{et=await Gu(Ue)}catch(ze){return be(ze instanceof Error?ze.message:"Could not import image"),!1}const at=et.type==="image/jpeg"?"jpg":"webp",Ke=new FormData;Ke.append("file",new File([et],`clean.${at}`,{type:et.type}));const Et=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ke});if(!Et.ok){const ze=await Et.json();return be(ze.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{ie(!1)}},[c,t,i,e.id,h]),C=nM(e,T,ge),X=e.cleanImagePath??E??null,re=((He=e.overlays)==null?void 0:He.length)??0,le=!dn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!ge&&!T,V=!ge&&!T&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Ao(e),he=(((Ce=e.overlays)==null?void 0:Ce.length)??0)>0?"Re-draft with AI":"AI draft lettering",_e=C.key==="convert"?{label:A?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=rM(e),Le=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||dn(e);return d.jsxs("div",{ref:te,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),X||dn(e)?d.jsx(jD,{storyName:t,assetPath:X,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Le?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:dn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[le?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:re>0?"Review lettering":"Open focused editor"}),V&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):_e?d.jsx("button",{onClick:_e.onClick,disabled:C.key==="convert"&&(A||I),"data-testid":_e.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:_e.label}):null,!le&&!_e&&V&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[T&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:A||I,"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:A?"Converting…":"Convert image"})]}),ge&&!T&&d.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:[S.map((Ue,et)=>d.jsx("p",{className:"text-[11px] text-error",children:Ue},et)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!dn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),ne(!0),setTimeout(()=>ne(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ue=>{var at;const et=(at=Ue.target.files)==null?void 0:at[0];et&&K(et),Ue.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var Ue;return(Ue=q.current)==null?void 0:Ue.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(Ue=>!Ue),disabled:R,"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:Y?"Hide Codex images":"Import from Codex"})]}),Y&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async Ue=>{await K(Ue)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.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."}),$==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!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:F?"Copied!":"Copy Codex task"})]}),$==="missing"&&f&&d.jsx("button",{onClick:_,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"}),fe&&d.jsx("p",{className:"text-xs text-error mt-1",children:fe})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||dn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ue,et)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[Ue.speaker,":"]})," ",Ue.text]},et))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var mr,Ot,oe;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,j]=w.useState(null),[I,te]=w.useState(null),[q,R]=w.useState(null),[ie,fe]=w.useState(!1),[be,B]=w.useState([]),[ne,F]=w.useState(!1),[G,Y]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[C,X]=w.useState(null),[re,le]=w.useState(null),[V,he]=w.useState(null),[_e,Me]=w.useState(!1),[Le,He]=w.useState(new Set),[Ce,Ue]=w.useState(new Map),[et,at]=w.useState(!1),[Ke,Et]=w.useState(null),[ze,_t]=w.useState(!1),[Te,Vt]=w.useState(null),ki=w.useRef(new Map),Ct=w.useRef(null),tt=t.replace(/\.md$/,"");w.useEffect(()=>{var O;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(te(c.cutId),Vt(c.cutId)),(O=S.current)==null||O.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ce;if(Te==null)return;const O=ki.current.get(Te);O&&((ce=O.scrollIntoView)==null||ce.call(O,{behavior:"smooth",block:"center"}),Vt(null))},[Te,x]);const Q=w.useCallback(async()=>{var O;try{const ce=await i(`/api/stories/${e}/cuts/${tt}`);if(ce.status===404){b(null);return}if(!ce.ok){const De=await ce.json();j(De.error||"Failed to load cuts");return}const ke=await ce.json();b(ke),j(null);try{const De=await i(`/api/stories/${e}/${t}`);if(De.ok){const Ee=await De.json(),Pe=typeof(Ee==null?void 0:Ee.content)=="string"?Ee.content:"",We=Array.isArray(ke==null?void 0:ke.cuts)?ke.cuts:[],rt=Pe.length>0&&KS(Pe,We).ready,Xe=(Ee==null?void 0:Ee.status)==="published"||(Ee==null?void 0:Ee.status)==="published-not-indexed";A({markdownReady:rt,published:Xe})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(O=v.current)==null||O.call(v)}catch{j("Failed to load cuts")}finally{M(!1)}},[i,e,tt,t]),xe=w.useCallback(async O=>!!(await i(`/api/stories/${e}/cuts/${tt}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok,[i,e,tt]),je=w.useCallback(async()=>{at(!1);try{const O=await i(`/api/stories/${e}/cuts/${tt}/detect-clean-images`);if(!O.ok)return;const ce=await O.json();He(new Set(Array.isArray(ce.detected)?ce.detected:[]));const ke=new Map,De=ce.stale;if(Array.isArray(De))for(const Ee of De){if(typeof(Ee==null?void 0:Ee.cutId)!="number"||typeof(Ee==null?void 0:Ee.message)!="string")continue;const Pe=ke.get(Ee.cutId)??[];Pe.push(Ee.message),ke.set(Ee.cutId,Pe)}Ue(ke),at(!0)}catch{}},[i,e,tt]),$e=w.useCallback(async()=>{Et(null);try{const O=await i(`/api/stories/${e}/cuts/${tt}/asset-diagnostics`);if(!O.ok)return;const ce=await O.json();Et(Array.isArray(ce.diagnostics)?ce.diagnostics:null)}catch{}},[i,e,tt]),nt=w.useCallback(async()=>{_t(!0);try{await Promise.all([Q(),je(),$e()])}finally{_t(!1)}},[Q,je,$e]),Wt=w.useCallback(async(O,ce={})=>{var Ee;if(!x)return!1;const ke=x.cuts.find(Pe=>Pe.id===O);if(!ke||!Ao(ke)||(((Ee=ke.overlays)==null?void 0:Ee.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const De=hy(ke);if(De.length===0)return le(`Cut ${ke.id}: no script lines available to draft.`),!1;he(O),le(null);try{const Pe={...x,cuts:x.cuts.map(rt=>rt.id===O?{...rt,overlays:De,aiDraft:_y(De)}:rt)};return await xe(Pe)?(le(`Cut ${ke.id}: AI draft ready`),await Q(),ce.openEditor&&R(O),!0):(le(`Cut ${ke.id}: AI draft failed`),!1)}finally{he(null)}},[x,xe,Q]),hi=w.useCallback(async()=>{if(!x)return;const O=x.cuts.filter(ce=>{var ke;return Ao(ce)&&(((ke=ce.overlays)==null?void 0:ke.length)??0)===0&&!ce.finalImagePath&&!ce.uploadedCid&&!ce.uploadedUrl});if(O.length===0){le("No unlettered cuts need an AI draft");return}Me(!0),le(null);try{const ce={...x,cuts:x.cuts.map(De=>{if(!O.some(Pe=>Pe.id===De.id))return De;const Ee=hy(De);return Ee.length>0?{...De,overlays:Ee,aiDraft:_y(Ee)}:De})};if(!await xe(ce)){le("AI draft failed");return}le(`AI draft ready for ${O.length} cut${O.length===1?"":"s"}`),await Q()}finally{Me(!1)}},[x,xe,Q]),Lt=w.useCallback(async()=>{$(!0),le(null),B([]);try{const O=await i(`/api/stories/${e}/cuts/${tt}/sync-clean-images`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Sync failed");else{const ke=Array.isArray(ce.synced)?ce.synced.length:0,De=Array.isArray(ce.cleared)?ce.cleared.length:0,Ee=Array.isArray(ce.rejected)?ce.rejected:[];Ee.length>0&&B(Ee.map(We=>`Cut ${We.cutId}: ${We.reason}`));const Pe=[];ke>0&&Pe.push(`Synced ${ke}`),De>0&&Pe.push(`Cleared ${De} stale path${De===1?"":"s"}`),le(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await je(),await $e()}}catch{le("Sync failed")}$(!1)},[i,e,tt,Q,je,$e]),yt=w.useCallback(async(O,ce)=>{try{const ke=await i(HS(e,ce));if(!ke.ok)return!1;const De=await ke.blob(),Ee=await Gu(new File([De],"clean.png",{type:De.type||"image/png"})),Pe=Ee.type==="image/jpeg"?"jpg":"webp",We=new FormData;return We.append("file",new File([Ee],`clean.${Pe}`,{type:Ee.type})),(await i(`/api/stories/${e}/cuts/${tt}/upload-clean/${O}`,{method:"POST",body:We})).ok}catch{return!1}},[i,e,tt]),Dt=w.useCallback(async O=>{K(!0),X(null);let ce=0;const ke=[];for(const De of O)await yt(De.cutId,De.pngPath)?ce++:ke.push(De.cutId);await nt(),K(!1),X(ke.length===0?`Converted ${ce} image${ce===1?"":"s"} to WebP`:`Converted ${ce}; ${ke.length} failed (Cut ${ke.join(", ")}) — try Convert image on each`)},[yt,nt]),Qe=w.useCallback(async()=>{var Ee;if(!x)return;F(!0),Y(""),B([]);const O=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),ce=[],ke=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>Y(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Jt.ok){const{cid:qn,url:xr}=await Jt.json();return{ok:!0,status:Jt.status,cid:qn,url:xr}}const Wi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:Wi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:Wi,waitMs:qn})=>Y(`Cut ${We.id} rate-limited — waiting ${Math.round(qn/1e3)}s before retry ${Jt}/${Wi}...`)});if(!Gt.ok){ce.push(`Cut ${We.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Mt,url:Ni}=Gt;(await i(`/api/stories/${e}/cuts/${tt}/set-uploaded/${We.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Mt,url:Ni})})).ok||ce.push(`Cut ${We.id}: failed to record upload`)}catch(rt){ce.push(`Cut ${We.id}: ${rt instanceof Error?rt.message:"failed"}`)}}if(ce.length>0){B(ce),F(!1),Y(""),Q();return}Y("Preparing episode for publishing…");const De=await i(`/api/stories/${e}/cuts/${tt}/generate-markdown`,{method:"POST"});if(De.ok){const Pe=await De.json();((Ee=Pe.warnings)==null?void 0:Ee.length)>0&&B(Pe.warnings)}F(!1),Y(""),Q()},[x,i,e,tt,a,Q]),di=w.useCallback(async()=>{T(!0),le(null);try{const O=await i(`/api/stories/${e}/cuts/${tt}/repair-asset-paths`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Repair failed");else{const ke=Array.isArray(ce.cleared)?ce.cleared.length:0;le(ke>0?`Cleared ${ke} stale path${ke===1?"":"s"}`:"No stale paths to clear"),await Q(),await je()}}catch{le("Repair failed")}T(!1)},[i,e,tt,Q,je]),[H,Se]=w.useState(!1),Oe=w.useCallback(async(O,ce=!0)=>{if(x){Se(!0);try{const ke=x.cuts.reduce((rt,Xe)=>Math.max(rt,Xe.id),0)+1,De={id:ke,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"},Ee=[...x.cuts];Ee.splice(Math.max(0,Math.min(O,Ee.length)),0,De);const Pe={...x,cuts:Ee},We=await i(`/api/stories/${e}/cuts/${tt}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(We.ok)ce?R(ke):te(ke),await Q();else{const rt=await We.json().catch(()=>({}));le(rt.error||"Could not add text panel")}}catch{le("Could not add text panel")}Se(!1)}},[x,i,e,tt,Q]),Ae=w.useCallback(()=>Oe((x==null?void 0:x.cuts.length)??0,!0),[Oe,x]);if(w.useEffect(()=>{Q(),je(),$e()},[Q,je,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[tt,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(O=>O.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:tt,language:s,authFetch:i,targetLabel:dn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(O,ce)=>{const ke={...x,cuts:x.cuts.map(Ee=>Ee.id===q?{...Ee,overlays:O,aiDraft:ce??Ee.aiDraft??null}:Ee)};if(!await xe(ke))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{R(null),Q()}});const Fe=x.cuts.reduce((O,ce)=>{const ke=r1(ce);return O[ke]++,O},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(O=>!dn(O)).length,ft=x.cuts.filter(O=>GS(O)).map(O=>O.id),ct=uD({cuts:x.cuts,published:U.published}),Kt=((mr=ct.steps.find(O=>O.key==="upload"))==null?void 0:mr.status)==="done",Ei=x.cuts.some(O=>O.finalImagePath&&!O.uploadedCid)||Kt&&!U.markdownReady,pt=(Ke??[]).filter(O=>O.state==="needs-conversion"&&O.convertiblePng).map(O=>({cutId:O.cutId,pngPath:O.convertiblePng})),qi=new Map(pt.map(O=>[O.cutId,O.pngPath])),jn=(Ke??[]).filter(O=>O.state==="needs-conversion"&&O.issue).map(O=>O.issue),sn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Ot=tt.match(/\d+/))==null?void 0:Ot[0])??"0",10)+1}`,Fn=typeof x.title=="string"?x.title:null,an=x.cuts.filter(O=>!dn(O)),gn={cuts:x.cuts.length,artwork:an.filter(O=>O.cleanImagePath||qi.has(O.id)).length,converted:an.filter(O=>O.cleanImagePath&&/\.(webp|jpe?g)$/i.test(O.cleanImagePath)).length,lettered:x.cuts.filter(O=>{var ce;return(((ce=O.overlays)==null?void 0:ce.length)??0)>0||!!O.finalImagePath}).length,uploaded:x.cuts.filter(O=>O.uploadedCid||O.uploadedUrl).length},ln=x.cuts.filter(O=>{var ce;return Ao(O)&&(((ce=O.overlays)==null?void 0:ce.length)??0)===0&&!O.finalImagePath&&!O.uploadedCid&&!O.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:sn}),Fn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Fn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[gn.cuts," cuts · ",gn.artwork," artwork found ·"," ",gn.converted," converted · ",gn.lettered," ","lettered · ",gn.uploaded," uploaded"]})]}),ln>0&&d.jsx("button",{onClick:hi,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${ln})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Fe.missing>0&&d.jsxs("span",{className:"text-muted",children:[Fe.missing," missing"]}),Fe.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.clean," clean"]}),Fe.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Fe.lettered," lettered"]}),Fe.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.uploaded," uploaded"]}),Fe.text>0&&d.jsxs("span",{className:"text-accent",children:[Fe.text," text ",Fe.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),B([]);try{const O=await i(`/api/stories/${e}/cuts/${tt}/generate-markdown`,{method:"POST"});if(O.ok){const ce=await O.json();B(ce.warnings||[])}}catch{}fe(!1)},disabled:ie,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:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:H,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:H?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:nt,disabled:ze,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:ze?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Lt,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"}),d.jsx("button",{onClick:Qe,disabled:ne||!(x!=null&&x.cuts.some(O=>O.finalImagePath&&!O.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),ft.length>0&&d.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:[ft.length===1?"Cut":"Cuts"," ",ft.join(", ")," ",ft.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",ft.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),et&&dt>0&&Fe.missing===0&&Ce.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),re&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:re}),pt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[pt.length," PNG image",pt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Dt(pt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),jn.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:jn.map((O,ce)=>d.jsx("li",{children:O},ce))})]})]}),Ke&&Ke.length>0&&(()=>{const O=tM(Ke),ce=Ke.filter(ke=>ke.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",O.uploaded," uploaded · ",O.finalReady," final ·"," ",O.cleanReady," clean · ",O.planned," planned",O.needsConversion>0?` · ${O.needsConversion} needs conversion`:"",O.missing>0?` · ${O.missing} missing`:""]}),ce.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ce.map(ke=>d.jsx("li",{children:ke.issue},ke.cutId))})]})})(),d.jsx(eM,{checklist:ct,issues:be,onFinish:Qe,finishing:ne,progressText:G,canFinish:Ei,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((O,ce)=>{var ke;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ce,beforeLabel:ce===0?"Episode opening":`After cut ${(ke=x.cuts[ce-1])==null?void 0:ke.id}`,afterLabel:`Before cut ${O.id}`,disabled:H,onAdd:()=>Oe(ce)}),d.jsx(sM,{cut:O,storyName:e,plotFile:tt,language:s,expanded:I===O.id,onToggle:()=>te(I===O.id?null:O.id),authFetch:i,onUpdated:()=>{Q(),je(),$e()},onOpenEditor:()=>R(O.id),detectedLocalClean:Le.has(O.id),onSyncClean:Lt,syncing:z,onAiDraft:()=>{Wt(O.id,{openEditor:!0})},aiDrafting:V===O.id,staleMessages:Ce.get(O.id)??[],onRepairStale:di,repairing:ge,conversionPng:qi.get(O.id)??null,onConvert:yt,converting:D,rowRef:De=>{De?ki.current.set(O.id,De):ki.current.delete(O.id)}})]},O.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(oe=x.cuts[x.cuts.length-1])==null?void 0:oe.id}`,afterLabel:"Episode ending",disabled:H,onAdd:()=>Oe(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 zp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function zo(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 dM(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 Pp(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 km(e){var s;const t=zp(e.fileContent);if(t)return!Pp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Pp(i)}function Em(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=zp(i);if(t==="genesis.md"){const p=a?zp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Lf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Of(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=Of(e.requiredBalance)??Of(e.creationFee),i=Of(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 _M={...cl,attributes:{...cl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E}){const[j,I]=w.useState(null),[te,q]=w.useState(!1),[R,ie]=w.useState("preview"),[fe,be]=w.useState("publish"),[B,ne]=w.useState("text"),[F,G]=w.useState(null),Y=w.useCallback((se,ye)=>{ie("edit"),G(Ne=>({cutId:se,openEditor:ye,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[U,A]=w.useState(""),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[C,X]=w.useState(null),[re,le]=w.useState(""),[V,he]=w.useState(""),[_e,Me]=w.useState(!1),[Le,He]=w.useState(null),[Ce,Ue]=w.useState(0),[et,at]=w.useState(0),[Ke,Et]=w.useState(null),[ze,_t]=w.useState(null),[Te,Vt]=w.useState(null),[ki,Ct]=w.useState(0),tt=w.useRef(null),Q=w.useRef(!1),[xe,je]=w.useState(!1),[$e,nt]=w.useState(sl[0]),[Wt,hi]=w.useState(ts[0]),[Lt,yt]=w.useState(!1),[Dt,Qe]=w.useState(null),[di,H]=w.useState(null),[Se,Oe]=w.useState(!1),[Ae,Ge]=w.useState(!1),[Fe,dt]=w.useState(!1),[ft,ct]=w.useState(null),[Kt,Ei]=w.useState(!1),pt=w.useRef(null),qi=w.useRef(null),[jn,sn]=w.useState(!1),[Fn,an]=w.useState(null),[gn,ln]=w.useState(null),[mr,Ot]=w.useState("unknown"),oe=w.useRef(!1),[O,ce]=w.useState(!1),[ke,De]=w.useState(!1),[Ee,Pe]=w.useState(null),[We,rt]=w.useState([]),[Xe,Nt]=w.useState(null),jt=w.useRef(null),Gt=w.useRef(null),Mt=w.useCallback(async()=>{if(!e||!t){I(null);return}const se=`${e}/${t}`,ye=Gt.current!==se;ye&&(Gt.current=se);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Je=await Ne.json();I(Je),(ye||!Q.current)&&(A(Je.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{q(!0),Mt().finally(()=>q(!1))},[Mt]),w.useEffect(()=>{if(!e||!t||R==="edit"&&ge)return;const se=setInterval(Mt,3e3);return()=>clearInterval(se)},[e,t,Mt,R,ge]);const[Ni,gr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){gr(null);return}let se=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{se||gr(ye?Lp(ye.cuts||[]):null)}).catch(()=>{se||gr(null)}),()=>{se=!0}},[Jt,e,i]);const Wi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!Wi||!e||!t){He(null),Ue(0),at(0),Et(null);return}let se=!1;const ye=t.replace(/\.md$/,"");return Et(null),(async()=>{try{const[Ne,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(se)return;if(!Je.ok){He("error"),Ue(0),at(0),Et(null);return}const Tt=await Je.json(),xi=Tt.cuts||[],Yn=Ne.ok?(await Ne.json()).content??"":"",Or=XS(Yn,xi);se||(He(Or.stage),Ue(Or.awaitingCount),at(Or.totalCuts),Et(Lp(xi)),Vt(typeof Tt.title=="string"?Tt.title:null))}catch{se||(He("error"),Ue(0),at(0),Et(null))}})(),()=>{se=!0}},[Wi,e,t,i,j==null?void 0:j.content,j==null?void 0:j.status,ki]),w.useEffect(()=>{if(!e){_t(null);return}let se=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{se||_t((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{se=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const se=yu(p);let ye=se??"";if(!se&&ze){const Je=ze.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(ye=yu(Je[1].replace(/\*+/g,"").trim())??"")}le(ye);let Ne=h&&ts.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!Ne&&ze){const Je=ze.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(Ne=ts.find(Tt=>Tt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(Ne),Me(f??!1)},[e,p,h,f,ze]);const qn=w.useCallback(se=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}).catch(()=>{})},[e,i]),xr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]);w.useCallback(async()=>{if(!e||!t)return;const se=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${se}/generate-markdown`,{method:"POST"})).ok&&(await Mt(),Ct(Ne=>Ne+1))}catch{}},[e,t,i,Mt]);const ei=w.useCallback(se=>{var Je;const ye=(Je=se.target.files)==null?void 0:Je[0];if(!ye)return;oe.current=!0,an(null),ln(null);const Ne=Sy(ye);if(Ne){Qe(null),H(Tt=>(Tt&&URL.revokeObjectURL(Tt),null)),pt.current&&(pt.current.value=""),ct(Ne),Ot("invalid");return}Qe(ye),H(Tt=>(Tt&&URL.revokeObjectURL(Tt),URL.createObjectURL(ye))),ct(null),Ot("selected")},[]),Dr=w.useCallback(async se=>{var Ne;const ye=(Ne=se.target.files)==null?void 0:Ne[0];if(qi.current&&(qi.current.value=""),!(!ye||!e)){oe.current=!0,an(null),sn(!0),ct(null);try{let Je;try{Je=await Gu(ye)}catch(Vn){Qe(null),H(Us=>(Us&&URL.revokeObjectURL(Us),null)),ct(Vn instanceof Error?Vn.message:"Could not import image");return}const Tt=Je.type==="image/jpeg"?"jpg":"webp",xi=new File([Je],`cover.${Tt}`,{type:Je.type}),Yn=new FormData;Yn.append("file",xi);const Or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Yn});if(!Or.ok){const Vn=await Or.json().catch(()=>({}));ct(Vn.error||"Cover import failed");return}Qe(xi),H(Vn=>(Vn&&URL.revokeObjectURL(Vn),URL.createObjectURL(xi))),ln(null),Ot("selected"),ct(null)}catch{ct("Cover import failed")}finally{sn(!1)}}},[e,i]),Tn=w.useCallback(async se=>{if(se.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(se.type)){Pe("Only WebP and JPEG images are accepted");return}De(!0),Pe(null);try{const Ne=new FormData;Ne.append("file",se);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Je.ok){const xi=await Je.json();throw new Error(xi.error||"Upload failed")}const Tt=await Je.json();rt(xi=>[...xi,{cid:Tt.cid,url:Tt.url}])}catch(Ne){Pe(Ne instanceof Error?Ne.message:"Upload failed")}finally{De(!1),jt.current&&(jt.current.value="")}},[i]),or=w.useCallback(se=>{var Ne;const ye=(Ne=se.target.files)==null?void 0:Ne[0];ye&&Tn(ye)},[Tn]),on=w.useCallback(async()=>{if(j!=null&&j.storylineId){Oe(!0),ct(null),Ei(!1);try{let se;if(Dt){const Ne=new FormData;Ne.append("file",Dt);const Je=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Je.ok){const xi=await Je.json();throw new Error(xi.error||"Cover upload failed")}se=(await Je.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:j.storylineId,...se!==void 0&&{coverCid:se},genre:$e,language:Wt,isNsfw:Lt})});if(!ye.ok){const Ne=await ye.json();throw new Error(Ne.error||"Update failed")}Ei(!0),Qe(null),se!==void 0&&(dt(!0),H(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Ot("unknown"),pt.current&&(pt.current.value="")),setTimeout(()=>Ei(!1),3e3)}catch(se){ct(se instanceof Error?se.message:"Update failed")}finally{Oe(!1)}}},[j==null?void 0:j.storylineId,Dt,$e,Wt,Lt,i]);w.useEffect(()=>{je(!1),Qe(null),H(null),ct(null),Ei(!1),Ge(!1),ce(!1),rt([]),Pe(null),an(null),ln(null),Ot("unknown"),oe.current=!1,ne("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!j||j.storylineId||j.status==="published"||j.status==="published-not-indexed"||oe.current)return;let se=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(se||!ye.ok)return;const Ne=await ye.json();if(se)return;if(!(Ne!=null&&Ne.found)){Ot("none");return}if(!Ne.valid){ln(Ne.error||"Detected cover asset is invalid and was not used"),Ot("invalid");return}const Je=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(se||!Je.ok)return;const Tt=await Je.blob(),xi=new File([Tt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(Sy(xi)||se||oe.current)return;Qe(xi),H(Yn=>(Yn&&URL.revokeObjectURL(Yn),URL.createObjectURL(xi))),an(Ne.path),Ot("detected")}catch{}})(),()=>{se=!0}},[e,t,j,j==null?void 0:j.status,j==null?void 0:j.storylineId,i]),w.useEffect(()=>{if(!xe||!(j!=null&&j.storylineId))return;Ge(!1);const se="https://plotlink.xyz";let ye=!1;return fetch(`${se}/api/storyline/${j.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!ye){if(!Ne){ct("Could not load current story metadata");return}if(Ne.genre){const Je=yu(Ne.genre);Je&&nt(Je)}if(Ne.language){const Je=ts.find(Tt=>Tt.toLowerCase()===Ne.language.toLowerCase());Je&&hi(Je)}Ne.isNsfw!==void 0&&yt(!!Ne.isNsfw),dt(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),Ge(!0)}}).catch(()=>{ye||ct("Could not load current story metadata")}),()=>{ye=!0}},[xe,j==null?void 0:j.storylineId]),w.useEffect(()=>{if(R!=="edit")return;const se=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),xr())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[R,xr]),w.useEffect(()=>{if((j==null?void 0:j.status)!=="published-not-indexed"||!j.publishedAt)return;const se=new Date(j.publishedAt).getTime(),ye=300*1e3,Ne=()=>{const Tt=Math.max(0,ye-(Date.now()-se));X(Tt)};Ne();const Je=setInterval(Ne,1e3);return()=>clearInterval(Je)},[j==null?void 0:j.status,j==null?void 0:j.publishedAt]);const St=C!==null&&C<=0,An=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!j)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const _r=(R==="edit"?U:(j==null?void 0:j.content)??"").length,fi=t==="genesis.md",xn=t?/^plot-\d+\.md$/.test(t):!1,Mi=c==="cartoon"&&xn,ni=c==="cartoon"&&fi,Mr=ni||Mi,Br=(j==null?void 0:j.status)==="published"||(j==null?void 0:j.status)==="published-not-indexed",xa=S&&Mr,Lr=ni?Ni?Ni.total:null:Mi?Le===null?null:et:null,_a=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Br,cutCount:Lr,cutProgress:ni?Ni:null}),pl=(ni||Mi)&&!Br,Wn=pl?Em({fileName:t,fileContent:(j==null?void 0:j.content)??"",storySlug:e??"",structureContent:ze,contentType:"cartoon",episodeTitle:Te}):null,ml=!!Wn&&zo(Wn,t),gl=Mi&&!Br&&!km({fileContent:(j==null?void 0:j.content)??"",episodeTitle:Te}),as=ni&&!Br?Sm((j==null?void 0:j.content)??""):null,ba=!!as&&as.blockers.length>0,Yu="w-full max-w-[32rem] rounded-xl border px-3 py-3",Vu={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Hs=se=>{if(!ni)return null;const ye=cM({hasSelectedCover:!!Dt,invalid:mr==="invalid",attached:se});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${Vu[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},Rn=ml||gl,xl=()=>{if(!pl||!Wn)return null;const se=fi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":ml?"true":"false","data-blocked":Rn?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[se,":"]})," ",d.jsx("span",{className:Rn?"text-error font-medium":"text-foreground",children:Wn})]}),ml?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",fi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):gl?d.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]})},_l=()=>as?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":ba?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),as.blockers.map((se,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:se},`b-${ye}`)),as.warnings.map((se,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:se},`w-${ye}`))]}):null,Gn=fi||xn?1e4:null,cr=!Br&&Gn!==null&&_r>Gn,Yo=(j==null?void 0:j.content)??"",ls=Br?{count:0,warnings:[]}:yM(Yo),bl=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:tt,value:U,onChange:se=>{A(se.target.value),T(!0),Q.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:ge?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:xr,disabled:!ge||z,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!xa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(j==null?void 0:j.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(j==null?void 0:j.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:j.indexError,children:"Published (not indexed)"}),(j==null?void 0:j.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${cr?"text-error font-medium":"text-muted"}`,children:[_r.toLocaleString(),Gn!==null?`/${Gn.toLocaleString()}`:" chars"]}),cr&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(_r-Gn).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",ge&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),R==="preview"?Mi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>be("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>be("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(gD,{content:(j==null?void 0:j.content)??"",stage:Le}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:Y})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:j!=null&&j.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:j.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Mi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ct(se=>se+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):ni?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>ne("text"),className:`px-2 py-0.5 text-[11px] rounded ${B==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ne("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${B==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ct(se=>se+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):bl})]}):bl,!xa&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:_a}):(j==null?void 0:j.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!St&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!j.txHash)){K(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:j.txHash,content:j.content,storylineId:j.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:j.txHash,storylineId:j.storylineId,contentCid:"",gasCost:""})}),Mt())}catch{}K(!1)}},disabled:D,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:D?"Retrying...":`Retry Index${An?` (${An})`:""}`}),xn&&d.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,se,K,_e)},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"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:ya?gi?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gi?"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."}),N.indexError&&d.jsx("p",{className:"text-error text-xs",children:N.indexError})]}):(N==null?void 0:N.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),N.storylineId&&d.jsx("a",{href:(()=>{var Ce;const re=`https://plotlink.xyz/story/${N.storylineId}`;if(!gi)return re;const ye=N.plotIndex!=null&&N.plotIndex>0?N.plotIndex:parseInt(((Ce=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ce[1])??"1");return`${re}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ei&&o&&N.storylineId&&(!N.authorAddress||N.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>je(re=>!re),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:xe?"Close Edit":"Edit Story"})]}),xe&&Ei&&N.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ea(Fe),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Qe(null),H(null),cn(null),Lt("unknown"),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:$e,onChange:re=>nt(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:dl.map(re=>d.jsx("option",{value:re,children:re},re))}),d.jsx("select",{value:Wt,onChange:re=>ui(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(re=>d.jsx("option",{value:re,children:re},re))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Bt,onChange:re=>yt(re.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:qn,disabled:Se||!Ae,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Se?"Saving...":Ae?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),ft&&d.jsx("span",{className:"text-error text-xs",children:ft})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Gi&&Ve&&Ve.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Ve.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.withClean,"/",Ve.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.withText,"/",Ve.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.uploaded,"/",Ve.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),jn&&ki&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ki.total," planned",ki.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ki.withClean," clean ·"," ",ki.withText," lettered ·"," ",ki.exported," exported ·"," ",ki.uploaded," uploaded"]})]}),(jn||Gi)&&_r&&d.jsxs("div",{className:`${ka} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:yl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:jn?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_r})]}),gi&&!Gi&&R==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:O,onChange:re=>ce(re.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),O&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 re;return(re=jt.current)==null?void 0:re.click()},onDragOver:re=>{re.preventDefault(),re.stopPropagation()},onDrop:re=>{var Ce;re.preventDefault(),re.stopPropagation();const ye=(Ce=re.dataTransfer.files)==null?void 0:Ce[0];ye&&Wi(ye)},children:[d.jsx("input",{ref:jt,type:"file",accept:"image/webp,image/jpeg",onChange:Ct,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Ee?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ne&&d.jsx("span",{className:"text-error text-xs",children:Ne}),We.map((re,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",re.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${re.url})`),Nt(ye),setTimeout(()=>Nt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Xe===ye?"Copied!":"Copy"})]})]},re.cid))]})]}),Ei&&c!=="cartoon"&&!(R==="edit"&&B==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ea(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{oe.current=!0,on(null),cn(null),Lt("unknown"),Qe(null),H(re=>(re&&URL.revokeObjectURL(re),null)),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Fi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:ar,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var re;return(re=Fi.current)==null?void 0:re.click()},disabled:Nn,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:Nn?"Importing…":"Import generated image (PNG ok)"}),Rt&&d.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."}),Un&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Un," — pick a file to override."]}),xn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[xn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&pr==="none"&&!Rt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),ft&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:ft})]})]})]}),!Or&&ls(),!Or&&os(),!Or&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ei&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:se,"data-testid":"publish-genre-select",onChange:re=>{le(re.target.value),re.target.value&&$n({genre:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${se?"border-border":"border-amber-500"}`,children:[!se&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),dl.map(re=>d.jsx("option",{value:re,children:re},re))]}),d.jsxs("select",{value:K,"data-testid":"publish-language-select",onChange:re=>{he(re.target.value),re.target.value&&$n({language:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(re=>d.jsx("option",{value:re,children:re},re))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(br.count>0){const ye=`This plot contains ${br.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,re,V,_e)},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"}),j.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${j.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:St?xn?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":xn?"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."}),j.indexError&&d.jsx("p",{className:"text-error text-xs",children:j.indexError})]}):(j==null?void 0:j.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),j.storylineId&&d.jsx("a",{href:(()=>{var Ne;const se=`https://plotlink.xyz/story/${j.storylineId}`;if(!xn)return se;const ye=j.plotIndex!=null&&j.plotIndex>0?j.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${se}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),j.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${j.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),fi&&o&&j.storylineId&&(!j.authorAddress||j.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>je(se=>!se),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:xe?"Close Edit":"Edit Story"})]}),xe&&fi&&j.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Hs(Fe),d.jsxs("div",{className:"flex items-start gap-3",children:[di&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:di,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Qe(null),H(null),ln(null),Ot("unknown"),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:ei,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:$e,onChange:se=>nt(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:sl.map(se=>d.jsx("option",{value:se,children:se},se))}),d.jsx("select",{value:Wt,onChange:se=>hi(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(se=>d.jsx("option",{value:se,children:se},se))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Lt,onChange:se=>yt(se.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:on,disabled:Se||!Ae,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Se?"Saving...":Ae?"Save Changes":"Loading..."}),Kt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),ft&&d.jsx("span",{className:"text-error text-xs",children:ft})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Mi&&Ke&&Ke.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Ke.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.withClean,"/",Ke.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.withText,"/",Ke.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.uploaded,"/",Ke.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),ni&&Ni&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Ni.total," planned",Ni.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Ni.withClean," clean ·"," ",Ni.withText," lettered ·"," ",Ni.exported," exported ·"," ",Ni.uploaded," uploaded"]})]}),(ni||Mi)&&_a&&d.jsxs("div",{className:`${Yu} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Lr===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:ni?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_a})]}),xn&&!Mi&&R==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:O,onChange:se=>ce(se.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),O&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 se;return(se=jt.current)==null?void 0:se.click()},onDragOver:se=>{se.preventDefault(),se.stopPropagation()},onDrop:se=>{var Ne;se.preventDefault(),se.stopPropagation();const ye=(Ne=se.dataTransfer.files)==null?void 0:Ne[0];ye&&Tn(ye)},children:[d.jsx("input",{ref:jt,type:"file",accept:"image/webp,image/jpeg",onChange:or,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:ke?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ee&&d.jsx("span",{className:"text-error text-xs",children:Ee}),We.map((se,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",se.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${se.url})`),Nt(ye),setTimeout(()=>Nt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Xe===ye?"Copied!":"Copy"})]})]},se.cid))]})]}),fi&&c!=="cartoon"&&!(R==="edit"&&B==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Hs(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[di&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:di,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{oe.current=!0,an(null),ln(null),Ot("unknown"),Qe(null),H(se=>(se&&URL.revokeObjectURL(se),null)),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:ei,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:qi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Dr,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var se;return(se=qi.current)==null?void 0:se.click()},disabled:jn,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:jn?"Importing…":"Import generated image (PNG ok)"}),Dt&&d.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."}),Fn&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Fn," — pick a file to override."]}),gn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[gn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&mr==="none"&&!Dt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),ft&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:ft})]})]})]}),!Mr&&xl(),!Mr&&_l(),!Mr&&d.jsxs("div",{className:"flex items-center gap-2",children:[fi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:re,"data-testid":"publish-genre-select",onChange:se=>{le(se.target.value),se.target.value&&qn({genre:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${re?"border-border":"border-amber-500"}`,children:[!re&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),sl.map(se=>d.jsx("option",{value:se,children:se},se))]}),d.jsxs("select",{value:V,"data-testid":"publish-language-select",onChange:se=>{he(se.target.value),se.target.value&&qn({language:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${V?"border-border":"border-amber-500"}`,children:[!V&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(se=>d.jsx("option",{value:se,children:se},se))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ls.count>0){const ye=`This plot contains ${ls.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(ye))return}const re=Ei?Rt:null;re?await(s==null?void 0:s(e,t,se,K,_e,re))&&(oe.current=!0,on(null),cn(null),Lt("unknown"),Qe(null),H(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),pt.current&&(pt.current.value="")):s==null||s(e,t,se,K,_e)},disabled:!!a||us||Ws||Vo||Ei&&(!se||!K)||Gi&&Le!=="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"}),Ei&&c==="cartoon"&&(!se||!K)&&d.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"}),Ei&&c!=="cartoon"&&!se&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ei&&c!=="cartoon"&&se&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),us&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Gi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Gi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Gi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",ke," of ",Je," ","still need an uploaded image"]})]}),Or&&d.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 →"}),br.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:br.warnings.map((re,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:re},ye))}),Ei&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:re=>{Me(re.target.checked),$n({isNsfw:re.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 r1(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(f=>!f.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 CM({progress:e,onOpenStoryInfo:t}){return d.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:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.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"}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]})]}),d.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 s1({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return r1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(Cm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function kM({storyName:e,authFetch:t,refreshKey:i=0,onCoachAction:s,onOpenStoryInfo:a}){const[o,c]=w.useState(void 0),h=JSON.stringify([e,i]),[p,f]=w.useState(null);return p!==h&&(c(void 0),f(h)),w.useEffect(()=>{let _=!1;return t(`/api/stories/${e}/progress`).then(x=>x.ok?x.json():null).then(x=>{_||c(EM(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?d.jsx(s1,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):d.jsx(Cm,{coach:null,showEmptyState:!0,onAction:s})}function EM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function NM({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 f=!1;return(async()=>{p(!0);try{const x=await t(`/api/stories/${e}/progress`),b=x.ok?await x.json():null;f||(c(b),p(!1))}catch{f||(c(null),p(!1))}})(),()=>{f=!0}},[e,t,a]),h?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):o.contentType==="cartoon"?d.jsx(BM,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(zM,{progress:o,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function a1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const l1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},o1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},jM={done:"✓",current:"◓",todo:"○"},TM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function c1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${TM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:jM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function wy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:l1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:o1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(c1,{item:h},p))})]})}function AM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function RM(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(DM(a));return s}function DM(e){return{label:e.label,status:e.status,detail:e.detail}}const MM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function BM({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,f=r1(e),_=d.jsx(s1,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,N)=>{E!=="view-progress"&&N&&i(t,N)}}),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=f==="story-info"?"current":p?"needs-action":"done",v=o?"done":f==="whitepaper"?"current":"not-started",S=e.episodes.find(E=>E.kind==="genesis")??null,j=e.episodes.filter(E=>E.kind==="plot");let D=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(a1,{progress:e}),d.jsx("div",{className:"border-b border-border","data-testid":"persistent-next-action",children:_}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(wy,{index:++D,title:"Define Story Info",status:b,items:x}),d.jsx(wy,{index:++D,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"}]}),S?d.jsx(Pf,{index:++D,ep:S,isActive:f===S.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++D,ep:MM,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),j.map(E=>d.jsx(Pf,{index:++D,ep:E,isActive:f===E.file,storyName:t,onOpenFile:i},E.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=AM(t,i),p=RM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:l1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:o1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(c1,{item:x},b))})]})}const LM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},Cy={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},OM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function zM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(a1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(ky,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(ky,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${Cy[o.state]}`,"aria-hidden":!0,children:LM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Cy[o.state]}`,children:OM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function ky({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const PM=[{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 IM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:PM.map(s=>{const a=s.key===t;return d.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 HM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[j,D]=w.useState(!1),[E,N]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[q,R]=w.useState(!1),[ie,fe]=w.useState(!1),[be,B]=w.useState(null),[ne,F]=w.useState(!1),[G,Y]=w.useState(null),[U,A]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),B(null),(async()=>{try{const[X,se]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!X.ok){C||(c(!0),a(!1));return}const le=await X.json(),K=se.ok?await se.json().catch(()=>null):null;if(C)return;p(le.title??""),_(le.description??""),b(Cu(le.genre)??""),S(le.language&&ts.find(he=>he.toLowerCase()===le.language.toLowerCase())||""),D(!!le.isNsfw),N(le.contentType==="fiction"?"fiction":"cartoon"),te((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{R(!0),fe(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:j};try{const X=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(X.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:j});else{const se=await X.json().catch(()=>({}));B(se.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,j,i]),ge=w.useCallback(async C=>{var se;const X=(se=C.target.files)==null?void 0:se[0];if(z.current&&(z.current.value=""),!!X){F(!0),B(null);try{let le;try{le=await Vu(X)}catch(Le){B(Le instanceof Error?Le.message:"Could not import image");return}const K=le.type==="image/jpeg"?"jpg":"webp",he=new File([le],`cover.${K}`,{type:le.type}),_e=new FormData;_e.append("file",he);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Me.ok){const Le=await Me.json().catch(()=>({}));B(Le.error||"Cover import failed.");return}te("present"),Y(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),T=w.useCallback(()=>{var X;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.`;(X=navigator.clipboard)==null||X.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const M=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",V=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),dl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${V}`,"data-testid":"story-info-cover-status",children:M}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:ne,"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:ne?"Importing…":"Import cover"}),d.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:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:ge,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:j,onChange:C=>{D(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,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"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function UM({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function $M({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var Ve,Et;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,j]=w.useState(!1),[D,E]=w.useState(null),[N,I]=w.useState(null),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(null),B=async()=>{try{const ze=await t(`/api/stories/${e}/cover-asset`),_t=ze.ok?await ze.json():null;if(!(_t!=null&&_t.found)||!_t.valid||!_t.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(_t.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Kt=await Te.blob();return new File([Kt],String(_t.path).split("/").pop()||"cover.webp",{type:_t.type||Kt.type})}catch{return null}};w.useEffect(()=>{let ze=!1;return(async()=>{v(!0),j(!1);try{const Te=await t(`/api/stories/${e}/progress`),Kt=Te.ok?await Te.json():null;if(ze)return;!Kt||!Array.isArray(Kt.episodes)?(j(!0),x(null)):x(Kt),v(!1)}catch{ze||(j(!0),x(null),v(!1))}})(),()=>{ze=!0}},[e,t,f]);const ne=((Et=(Ve=_==null?void 0:_.episodes)==null?void 0:Ve.find(ze=>!ze.published))==null?void 0:Et.file)??null,F=ne==="genesis.md",G=JSON.stringify([ne??"",f]),[Y,U]=w.useState(null);if(Y!==G&&(U(G),I(null),q(null),ie(null),be(null)),w.useEffect(()=>{if(!ne)return;let ze=!1;const _t=ne.replace(/\.md$/,"");return(async()=>{var Te;try{const Kt=[t(`/api/stories/${e}/${ne}`),t(`/api/stories/${e}/cuts/${_t}`)];F&&Kt.push(t(`/api/stories/${e}/structure.md`));const[mi,wt,et]=await Promise.all(Kt);if(ze)return;if(I(mi.ok?(await mi.json()).content??"":""),wt.ok){const Q=await wt.json();if(ze)return;q(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else q(null),ie(null);be(F&&et&&et.ok?((Te=await et.json())==null?void 0:Te.content)??null:null)}catch{ze||(I(""),q(null),ie(null),be(null))}})(),()=>{ze=!0}},[ne,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(ze=>!ze.published);if(!A)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=A.cuts,$=_.cover==="present",ge=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",M=A.state==="blocked",V=A.file==="genesis.md",C=!V||!!c&&!!h,X=!!o&&o===A.file,se=N!==null,le=se?Em({fileName:A.file,fileContent:N??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:R}):null,K=!!le&&Io(le,A.file),he=!V&&se&&!km({fileContent:N??"",episodeTitle:R}),_e=K||he,Me=V&&se?ym(N??""):null,Le=!!Me&&Me.blockers.length>0,He=!V&&se&&te!==null?VS(N??"",te):null,ke=He&&He.stage==="error"?He.issues:[],Je=T&&C&&(se&&(V||te!==null))&&!_e&&!Le&&!X&&!!a,at=async()=>{if(!(!Je||!a)){E(null);try{const ze=V?await B():null;await a(e,A.file,c??"",h??"",!!p,ze)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",A.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:ge.map((ze,_t)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":ze.status,children:[d.jsx("span",{className:`flex-shrink-0 ${ze.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:ze.status==="done"?"✓":"○"}),d.jsx("span",{className:ze.status==="done"?"text-foreground":"text-muted",children:ze.label}),ze.detail&&d.jsxs("span",{className:"text-muted",children:["· ",ze.detail]})]},_t))}),le&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[V?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:le})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",V?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",le,"” 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]}),Me&&d.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":Le?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),Me.blockers.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ze},`b-${_t}`)),Me.warnings.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ze},`w-${_t}`))]}),ke.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),XS(ke).map(ze=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${ze.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:ze.title})},ze.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:ke.map((ze,_t)=>d.jsx("li",{className:"font-mono break-words",children:ze},_t))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.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)"}),V&&!C&&d.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&&d.jsxs("button",{onClick:()=>i(e,A.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 ",A.label," to finish ",M?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!Je,"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:Je?void 0:"Finish the remaining steps above first",children:X?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:M?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),D&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:D})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:A.file})]}),d.jsxs("p",{children:["State: ",A.state," — ",A.summary]}),d.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 FM(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 qM(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?Io(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=FM(i,s);return a?Io(a,t)||Ip(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 WM(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 u1="plotlink-panel-ratio",GM=.6,Ey=300,If=224,Hf=6;function YM(){try{const e=localStorage.getItem(u1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return GM}function Ny(e,t){if(t<=0)return e;const i=Ey/t,s=1-Ey/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,j]=w.useState(null),[D,E]=w.useState(null),[N,I]=w.useState(YM),[te,q]=w.useState([]),[R,ie]=w.useState(!1),[fe,be]=w.useState(""),[B,ne]=w.useState(""),[F,G]=w.useState(""),[Y,U]=w.useState("English"),[A,z]=w.useState("normal"),[$,ge]=w.useState("claude"),[T,M]=w.useState(null),[V,C]=w.useState(!1),[X,se]=w.useState({}),[le,K]=w.useState({}),[he,_e]=w.useState(new Set),[Me,Le]=w.useState(new Set),[He,ke]=w.useState({}),[Ue,Je]=w.useState({}),[at,Ve]=w.useState({}),[Et,ze]=w.useState({}),[_t,Te]=w.useState({}),[Kt,mi]=w.useState({}),[wt,et]=w.useState(!1),[Q,xe]=w.useState(!0),je=w.useRef(new Map),$e=w.useRef(new Map),nt=w.useRef(new Map),Wt=w.useRef(new Map),ui=w.useRef(new Set),Bt=w.useRef(null),yt=w.useRef(null),Rt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.address&&E(oe.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(oe=>oe.ok?oe.json():null).then(oe=>{oe&&M(oe)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(u1,String(N))}catch{}},[N]),w.useEffect(()=>{const oe=()=>{if(!yt.current)return;const O=yt.current.getBoundingClientRect().width-If-Hf;I(ce=>Ny(ce,O))};return window.addEventListener("resize",oe),oe(),()=>window.removeEventListener("resize",oe)},[]);const Qe=w.useCallback(()=>{be(""),ne(""),G(""),z("normal"),ge("claude"),ie(!0)},[]),hi=w.useCallback(async(oe,O,ce,Ee)=>{const De=fe.trim();if(!De)return;const Ne=oe==="cartoon"?"codex":Ee;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:O,genre:F||void 0,contentType:oe,agentMode:ce,agentProvider:Ne})});if(!Pe.ok)return;const We=await Pe.json();ie(!1),ke(rt=>({...rt,[We.name]:oe})),Je(rt=>({...rt,[We.name]:O})),F&&Ve(rt=>({...rt,[We.name]:F})),K(rt=>({...rt,[We.name]:Ne})),ce==="bypass"&&se(rt=>({...rt,[We.name]:!0})),s(We.name),o(null)}catch{}},[t,fe,B,F]);w.useEffect(()=>{if(te.length===0)return;const oe=setInterval(async()=>{try{const O=await t("/api/stories");if(!O.ok)return;const ce=await O.json(),Ee=new Set(ce.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of Ee)if(!ui.current.has(De)&&te.length>0){const Ne=te[0],Pe=je.current.get(Ne)||"fiction",We=$e.current.get(Ne)||"English",rt=nt.current.get(Ne)||"normal",Xe=Wt.current.get(Ne)||"claude";let Nt=!1;Bt.current&&(Nt=await Bt.current(Ne,De,{contentType:Pe,language:We,agentMode:rt,agentProvider:Xe}).catch(()=>!1)),Nt&&(q(jt=>jt.slice(1)),je.current.delete(Ne),$e.current.delete(Ne),nt.current.delete(Ne),Wt.current.delete(Ne),rt==="bypass"&&se(jt=>{const Gt={...jt,[De]:!0};return delete Gt[Ne],Gt}),K(jt=>{const Gt={...jt,[De]:Xe};return delete Gt[Ne],Gt}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:We,agentMode:rt,agentProvider:Xe})}).catch(()=>{})),s(De),o(null)}ui.current=Ee}catch{}},3e3);return()=>clearInterval(oe)},[t,te]),w.useEffect(()=>{t("/api/stories").then(oe=>{if(oe.ok)return oe.json()}).then(oe=>{oe!=null&&oe.stories&&(ui.current=new Set(oe.stories.filter(O=>O.name!=="_example").map(O=>O.name)))}).catch(()=>{})},[t]);const H=w.useCallback((oe,O)=>{s(oe),o(O),h(null)},[]),Se=w.useRef(null),Oe=w.useCallback(async oe=>{var O,ce,Ee,De;Se.current=oe,s(oe),o(null),h(null);try{const Ne=await t(`/api/stories/${oe}`);if(Ne.ok&&Se.current===oe){const Pe=await Ne.json();if(Pe.contentType==="cartoon")return;const We=Pe.files||[],Xe=((O=We.map(Nt=>{var jt;return{file:Nt.file,num:(jt=Nt.file.match(/^plot-(\d+)\.md$/))==null?void 0:jt[1]}}).filter(Nt=>Nt.num!=null).sort((Nt,jt)=>parseInt(jt.num)-parseInt(Nt.num))[0])==null?void 0:O.file)??((ce=We.find(Nt=>Nt.file==="genesis.md"))==null?void 0:ce.file)??((Ee=We.find(Nt=>Nt.file==="structure.md"))==null?void 0:Ee.file)??((De=We[0])==null?void 0:De.file);Xe&&Se.current===oe&&o(Xe)}}catch{}},[t]),Ae=w.useCallback(oe=>{oe.preventDefault(),Rt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const O=Ee=>{if(!Rt.current||!yt.current)return;const De=yt.current.getBoundingClientRect(),Ne=De.width-If-Hf,Pe=Ee.clientX-De.left-If;I(Ny(Pe/Ne,Ne))},ce=()=>{Rt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",ce)};window.addEventListener("mousemove",O),window.addEventListener("mouseup",ce)},[]),Ge=w.useCallback(async(oe,O,ce,Ee,De,Ne)=>{var Xe;f(O),v("Reading file..."),j(null);let Pe=!1,We=null,rt=!1;try{const Nt=await t(`/api/stories/${oe}/${O}`);if(!Nt.ok)throw new Error("Failed to read file");const jt=await Nt.json(),Gt=He[oe];let Dt=null,ki=null;if(O==="genesis.md")try{const ei=await t(`/api/stories/${oe}/structure.md`);ei.ok&&(Dt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${oe}/cuts/${O.replace(/\.md$/,"")}`);ei.ok&&(ki=(await ei.json()).title??null)}catch{}const mr=Em({fileName:O,fileContent:jt.content,storySlug:oe,structureContent:Dt,contentType:Gt,episodeTitle:ki});if(Gt==="cartoon"&&Io(mr,O))return v(O==="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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/)&&!km({fileContent:jt.content,episodeTitle:ki}))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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O==="genesis.md"){const ei=ym(jt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(O.match(/^plot-\d+\.md$/)){if(pM(jt)){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(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${oe}`);if(ei.ok){const Fn=(await ei.json()).files.find(ar=>ar.file==="genesis.md"&&ar.storylineId);Jt=Fn==null?void 0:Fn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Br=await ei.json();if(gM(Br))return j(xM(Br)),f(null),v(""),!1}}catch{}v("Publishing...");const qi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:oe,fileName:O,title:mr,content:jt.content,genre:ce,language:Ee,isNsfw:De,storylineId:Jt,...Sy(He,oe,Jt)?{contentType:Sy(He,oe,Jt)}:{}})});if(!qi.ok){const ei=await qi.json();throw new Error(ei.error||"Publish failed")}const $n=(Xe=qi.body)==null?void 0:Xe.getReader(),gr=new TextDecoder;if($n)for(;;){const{done:ei,value:Br}=await $n.read();if(ei)break;const ar=gr.decode(Br).split(` -`).filter(Wi=>Wi.startsWith("data: "));for(const Wi of ar)try{const Ct=JSON.parse(Wi.slice(6));if(Ct.step&&v(Ct.message||Ct.step),Ct.step==="done"&&Ct.txHash){if(rt=!0,await t(`/api/stories/${oe}/${O}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Ct.txHash,storylineId:Ct.storylineId,plotIndex:Ct.plotIndex,contentCid:Ct.contentCid,gasCost:Ct.gasCost,indexError:Ct.indexError,authorAddress:D})}),x(qn=>qn+1),Ne&&O==="genesis.md"&&Ct.storylineId){v("Uploading cover...");let qn=null;try{qn=await uM(t,Ct.storylineId,Ne)}catch{}qn||(Pe=!0)}if(Gt==="cartoon"&&Ct.storylineId)try{const qn=O!=="genesis.md",ya=`storylineId=${Ct.storylineId}`+(qn&&Ct.plotIndex!=null?`&plotIndex=${Ct.plotIndex}`:""),Lr=await t(`/api/publish/public-title?${ya}`);if(Lr.ok){const Fs=await Lr.json(),xr=qn?{plots:Fs.plotTitle!=null?[{plotIndex:Ct.plotIndex,title:Fs.plotTitle}]:[]}:{title:Fs.storylineTitle},Ei=qM({fileName:O,detail:xr,plotIndex:Ct.plotIndex});Ei.ok||(We=WM(Ei))}}catch{}}}catch{}}We&&j(We),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Nt){const jt=Nt instanceof Error?Nt.message:"Publish failed";v(`Error: ${jt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return rt&&!Pe},[t,He,D]),Fe=w.useCallback(oe=>{oe.startsWith("_new_")&&(q(O=>O.filter(ce=>ce!==oe)),je.current.delete(oe),$e.current.delete(oe),nt.current.delete(oe),Wt.current.delete(oe),se(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}),K(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}))},[]);w.useEffect(()=>{const oe=ce=>{_e(new Set(ce.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Le(new Set(ce.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const Ee={},De={},Ne={},Pe={},We={},rt={};for(const Xe of ce)Ee[Xe.name]=Xe.contentType||"fiction",De[Xe.name]=Xe.language,Ne[Xe.name]=Xe.genre,Pe[Xe.name]=Xe.isNsfw,We[Xe.name]=Xe.agentProvider,Xe.title&&(rt[Xe.name]=Xe.title);ke(Ee),Je(De),Ve(Ne),ze(Pe),mi(We),Te(rt)};t("/api/stories").then(ce=>ce.ok?ce.json():null).then(ce=>{ce!=null&&ce.stories&&oe(ce.stories)}).catch(()=>{});const O=setInterval(async()=>{try{const ce=await t("/api/stories");if(ce.ok){const Ee=await ce.json();oe(Ee.stories)}}catch{}},5e3);return()=>clearInterval(O)},[t]);const dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",ft=!!T&&!dt,ct=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const oe=i;if((await t(`/api/stories/${oe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){mi(ce=>({...ce,[oe]:"codex"})),K(ce=>({...ce,[oe]:"codex"}));try{const ce=await t("/api/stories");if(ce.ok){const Ee=await ce.json();if(Ee!=null&&Ee.stories){const De={};for(const Ne of Ee.stories)De[Ne.name]=Ne.agentProvider;mi(De)}}}catch{}}},[t,i]),Ci=w.useCallback(oe=>{i===oe&&(s(null),o(null))},[i]),pt=i?le[i]??Kt[i]:void 0,Fi=Of(i,He,je.current),Nn=mM(Fi,pt,i),ln=!!i&&Fi==="cartoon",Un=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",on=w.useCallback(oe=>{const O=i;if(O)switch(oe){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":H(O,"structure.md");break;case"genesis":H(O,"genesis.md");break;case"publish":h("publish");break}},[i,H]),xn=w.useCallback((oe,O)=>{const ce=i;if(ce)switch(oe){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":O&&H(ce,O);break}},[i,H]),cn=w.useCallback(oe=>{i&&(oe.genre!==void 0&&Ve(O=>({...O,[i]:oe.genre||void 0})),oe.language!==void 0&&Je(O=>({...O,[i]:oe.language||void 0})),oe.isNsfw!==void 0&&ze(O=>({...O,[i]:oe.isNsfw})))},[i]),pr=w.useCallback(oe=>{et(oe),xe(!oe)},[]),Lt=wt&&!Q;return d.jsxs("div",{ref:yt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Lt?"stories-focused-lettering-mode":"stories-default-layout",children:[!Lt&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(DC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:H,onNewStory:Qe,untitledSessions:te})}),!Lt&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${N} 0 0`},children:d.jsx(rN,{token:e,storyName:i,authFetch:t,onSelectStory:Oe,onDestroySession:Fe,onArchiveStory:Ci,confirmedStories:he,renameRef:Bt,bypassStories:X,agentProviders:le,readiness:T,contentType:Of(i,He,je.current),needsProviderRepair:Nn,onRepairProvider:Vt})}),!Lt&&d.jsx("div",{onMouseDown:Ae,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Lt?{flex:"1 0 0"}:{flex:`${1-N} 0 0`},children:[!wt&&ln&&i&&d.jsx(IM,{storyTitle:_t[i]||i,active:Un,onSelect:on}),!wt&&ln&&i&&c!==null&&d.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:d.jsx(kM,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:xn,onOpenStoryInfo:()=>h("story-info")})}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:ln&&c==="story-info"&&i?d.jsx(HM,{storyName:i,authFetch:t,onSaved:cn}):ln&&c==="episodes"&&i?d.jsx(UM,{storyName:i,authFetch:t,onOpenFile:H}):ln&&c==="publish"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:at[i],language:Ue[i],isNsfw:Et[i],refreshKey:_}):i&&!a?d.jsx(NM,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info")}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:D,contentType:Of(i,He,je.current)||"fiction",language:i?Ue[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?Et[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:oe=>i&&H(i,oe),onViewPublish:()=>h("publish"),focusedLetteringMode:wt,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:pr,onFocusedLetteringWorkspaceVisibleChange:xe})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.jsx("button",{type:"button",onClick:()=>j(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:oe=>be(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:oe=>ne(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:oe=>G(oe.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:[d.jsx("option",{value:"",children:"— Select later —"}),dl.map(oe=>d.jsx("option",{value:oe,children:oe},oe))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:Y,onChange:oe=>U(oe.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:ts.map(oe=>d.jsx("option",{value:oe,children:oe},oe))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:A,onChange:oe=>z(oe.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:oe=>ge(oe.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>hi("fiction",Y,A,$),disabled:!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>hi("cartoon",Y,A,"codex"),disabled:ft||!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Up}),T&&T.codex.installed&&!Eu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:ct,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:V?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!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 VM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 XM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Ry,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(TC,{token:e}),i==="wallet-setup"&&d.jsx(VM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(NC,{token:e,onLogout:t})]})]})}function ZM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(XM,{token:e,onLogout:p}):d.jsx(kC,{onLogin:c}):d.jsx(EC,{onSetup:h})}CC.createRoot(document.getElementById("root")).render(d.jsx(gC.StrictMode,{children:d.jsx(ZM,{})}));export{zp as M,No as a,US as b,UD as c,U3 as d,Eo as l,bm as s,GS as t,i4 as v}; +Publish now?`;if(!window.confirm(ye))return}const se=fi?Dt:null;se?await(s==null?void 0:s(e,t,re,V,_e,se))&&(oe.current=!0,an(null),ln(null),Ot("unknown"),Qe(null),H(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),pt.current&&(pt.current.value="")):s==null||s(e,t,re,V,_e)},disabled:!!a||cr||Rn||ba||fi&&(!re||!V)||Mi&&Le!=="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"}),fi&&c==="cartoon"&&(!re||!V)&&d.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"}),fi&&c!=="cartoon"&&!re&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),fi&&c!=="cartoon"&&re&&!V&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),cr&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Mi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Mi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Mi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",Ce," of ",et," ","still need an uploaded image"]})]}),Mr&&d.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 →"}),ls.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:ls.warnings.map((se,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:se},ye))}),fi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:se=>{Me(se.target.checked),qn({isNsfw:se.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Ip({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Hp({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Ip,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Hp,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Hp,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Ip,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Ip,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Hp,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function du({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(du,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(du,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(du,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(du,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Bu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Bu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Bu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(zf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(zf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(zf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function zf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Bu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Bu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,j]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[q,R]=w.useState(!1),[ie,fe]=w.useState(!1),[be,B]=w.useState(null),[ne,F]=w.useState(!1),[G,Y]=w.useState(null),[U,A]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),B(null),(async()=>{try{const[X,re]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!X.ok){C||(c(!0),a(!1));return}const le=await X.json(),V=re.ok?await re.json().catch(()=>null):null;if(C)return;p(le.title??""),_(le.description??""),b(yu(le.genre)??""),S(le.language&&ts.find(he=>he.toLowerCase()===le.language.toLowerCase())||""),M(!!le.isNsfw),j(le.contentType==="fiction"?"fiction":"cartoon"),te((V==null?void 0:V.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{R(!0),fe(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const X=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(X.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const re=await X.json().catch(()=>({}));B(re.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),ge=w.useCallback(async C=>{var re;const X=(re=C.target.files)==null?void 0:re[0];if(z.current&&(z.current.value=""),!!X){F(!0),B(null);try{let le;try{le=await Gu(X)}catch(Le){B(Le instanceof Error?Le.message:"Could not import image");return}const V=le.type==="image/jpeg"?"jpg":"webp",he=new File([le],`cover.${V}`,{type:le.type}),_e=new FormData;_e.append("file",he);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Me.ok){const Le=await Me.json().catch(()=>({}));B(Le.error||"Cover import failed.");return}te("present"),Y(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),T=w.useCallback(()=>{var X;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.`;(X=navigator.clipboard)==null||X.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",K=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),sl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${K}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:ne,"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:ne?"Importing…":"Import cover"}),d.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:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:ge,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,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"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var Ke,Et;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[j,I]=w.useState(null),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(null),B=async()=>{try{const ze=await t(`/api/stories/${e}/cover-asset`),_t=ze.ok?await ze.json():null;if(!(_t!=null&&_t.found)||!_t.valid||!_t.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(_t.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Vt=await Te.blob();return new File([Vt],String(_t.path).split("/").pop()||"cover.webp",{type:_t.type||Vt.type})}catch{return null}};w.useEffect(()=>{let ze=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),Vt=Te.ok?await Te.json():null;if(ze)return;!Vt||!Array.isArray(Vt.episodes)?(N(!0),x(null)):x(Vt),v(!1)}catch{ze||(N(!0),x(null),v(!1))}})(),()=>{ze=!0}},[e,t,f]);const ne=((Et=(Ke=_==null?void 0:_.episodes)==null?void 0:Ke.find(ze=>!ze.published))==null?void 0:Et.file)??null,F=ne==="genesis.md",G=JSON.stringify([ne??"",f]),[Y,U]=w.useState(null);if(Y!==G&&(U(G),I(null),q(null),ie(null),be(null)),w.useEffect(()=>{if(!ne)return;let ze=!1;const _t=ne.replace(/\.md$/,"");return(async()=>{var Te;try{const Vt=[t(`/api/stories/${e}/${ne}`),t(`/api/stories/${e}/cuts/${_t}`)];F&&Vt.push(t(`/api/stories/${e}/structure.md`));const[ki,Ct,tt]=await Promise.all(Vt);if(ze)return;if(I(ki.ok?(await ki.json()).content??"":""),Ct.ok){const Q=await Ct.json();if(ze)return;q(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else q(null),ie(null);be(F&&tt&&tt.ok?((Te=await tt.json())==null?void 0:Te.content)??null:null)}catch{ze||(I(""),q(null),ie(null),be(null))}})(),()=>{ze=!0}},[ne,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(ze=>!ze.published);if(!A)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=A.cuts,$=_.cover==="present",ge=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",D=A.state==="blocked",K=A.file==="genesis.md",C=!K||!!c&&!!h,X=!!o&&o===A.file,re=j!==null,le=re?Em({fileName:A.file,fileContent:j??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:R}):null,V=!!le&&zo(le,A.file),he=!K&&re&&!km({fileContent:j??"",episodeTitle:R}),_e=V||he,Me=K&&re?Sm(j??""):null,Le=!!Me&&Me.blockers.length>0,He=!K&&re&&te!==null?XS(j??"",te):null,Ce=He&&He.stage==="error"?He.issues:[],et=T&&C&&(re&&(K||te!==null))&&!_e&&!Le&&!X&&!!a,at=async()=>{if(!(!et||!a)){E(null);try{const ze=K?await B():null;await a(e,A.file,c??"",h??"",!!p,ze)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",A.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:ge.map((ze,_t)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":ze.status,children:[d.jsx("span",{className:`flex-shrink-0 ${ze.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:ze.status==="done"?"✓":"○"}),d.jsx("span",{className:ze.status==="done"?"text-foreground":"text-muted",children:ze.label}),ze.detail&&d.jsxs("span",{className:"text-muted",children:["· ",ze.detail]})]},_t))}),le&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":V?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[K?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:le})]}),V?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",K?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",le,"” 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]}),Me&&d.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":Le?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),Me.blockers.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ze},`b-${_t}`)),Me.warnings.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ze},`w-${_t}`))]}),Ce.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(Ce).map(ze=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${ze.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:ze.title})},ze.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:Ce.map((ze,_t)=>d.jsx("li",{className:"font-mono break-words",children:ze},_t))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.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)"}),K&&!C&&d.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&&d.jsxs("button",{onClick:()=>i(e,A.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 ",A.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!et,"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:et?void 0:"Finish the remaining steps above first",children:X?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:A.file})]}),d.jsxs("p",{children:["State: ",A.state," — ",A.summary]}),d.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 qM(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 WM(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?zo(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=qM(i,s);return a?zo(a,t)||Pp(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,Pf=224,If=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[j,I]=w.useState(VM),[te,q]=w.useState([]),[R,ie]=w.useState(!1),[fe,be]=w.useState(""),[B,ne]=w.useState(""),[F,G]=w.useState(""),[Y,U]=w.useState("English"),[A,z]=w.useState("normal"),[$,ge]=w.useState("claude"),[T,D]=w.useState(null),[K,C]=w.useState(!1),[X,re]=w.useState({}),[le,V]=w.useState({}),[he,_e]=w.useState(new Set),[Me,Le]=w.useState(new Set),[He,Ce]=w.useState({}),[Ue,et]=w.useState({}),[at,Ke]=w.useState({}),[Et,ze]=w.useState({}),[_t,Te]=w.useState({}),[Vt,ki]=w.useState({}),[Ct,tt]=w.useState(!1),[Q,xe]=w.useState(!0),je=w.useRef(new Map),$e=w.useRef(new Map),nt=w.useRef(new Map),Wt=w.useRef(new Map),hi=w.useRef(new Set),Lt=w.useRef(null),yt=w.useRef(null),Dt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.address&&E(oe.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(oe=>oe.ok?oe.json():null).then(oe=>{oe&&D(oe)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(j))}catch{}},[j]),w.useEffect(()=>{const oe=()=>{if(!yt.current)return;const O=yt.current.getBoundingClientRect().width-Pf-If;I(ce=>jy(ce,O))};return window.addEventListener("resize",oe),oe(),()=>window.removeEventListener("resize",oe)},[]);const Qe=w.useCallback(()=>{be(""),ne(""),G(""),z("normal"),ge("claude"),ie(!0)},[]),di=w.useCallback(async(oe,O,ce,ke)=>{const De=fe.trim();if(!De)return;const Ee=oe==="cartoon"?"codex":ke;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:O,genre:F||void 0,contentType:oe,agentMode:ce,agentProvider:Ee})});if(!Pe.ok)return;const We=await Pe.json();ie(!1),Ce(rt=>({...rt,[We.name]:oe})),et(rt=>({...rt,[We.name]:O})),F&&Ke(rt=>({...rt,[We.name]:F})),V(rt=>({...rt,[We.name]:Ee})),ce==="bypass"&&re(rt=>({...rt,[We.name]:!0})),s(We.name),o(null)}catch{}},[t,fe,B,F]);w.useEffect(()=>{if(te.length===0)return;const oe=setInterval(async()=>{try{const O=await t("/api/stories");if(!O.ok)return;const ce=await O.json(),ke=new Set(ce.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of ke)if(!hi.current.has(De)&&te.length>0){const Ee=te[0],Pe=je.current.get(Ee)||"fiction",We=$e.current.get(Ee)||"English",rt=nt.current.get(Ee)||"normal",Xe=Wt.current.get(Ee)||"claude";let Nt=!1;Lt.current&&(Nt=await Lt.current(Ee,De,{contentType:Pe,language:We,agentMode:rt,agentProvider:Xe}).catch(()=>!1)),Nt&&(q(jt=>jt.slice(1)),je.current.delete(Ee),$e.current.delete(Ee),nt.current.delete(Ee),Wt.current.delete(Ee),rt==="bypass"&&re(jt=>{const Gt={...jt,[De]:!0};return delete Gt[Ee],Gt}),V(jt=>{const Gt={...jt,[De]:Xe};return delete Gt[Ee],Gt}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:We,agentMode:rt,agentProvider:Xe})}).catch(()=>{})),s(De),o(null)}hi.current=ke}catch{}},3e3);return()=>clearInterval(oe)},[t,te]),w.useEffect(()=>{t("/api/stories").then(oe=>{if(oe.ok)return oe.json()}).then(oe=>{oe!=null&&oe.stories&&(hi.current=new Set(oe.stories.filter(O=>O.name!=="_example").map(O=>O.name)))}).catch(()=>{})},[t]);const H=w.useCallback((oe,O)=>{s(oe),o(O),h(null)},[]),Se=w.useRef(null),Oe=w.useCallback(async oe=>{var O,ce,ke,De;Se.current=oe,s(oe),o(null),h(null);try{const Ee=await t(`/api/stories/${oe}`);if(Ee.ok&&Se.current===oe){const Pe=await Ee.json();if(Pe.contentType==="cartoon")return;const We=Pe.files||[],Xe=((O=We.map(Nt=>{var jt;return{file:Nt.file,num:(jt=Nt.file.match(/^plot-(\d+)\.md$/))==null?void 0:jt[1]}}).filter(Nt=>Nt.num!=null).sort((Nt,jt)=>parseInt(jt.num)-parseInt(Nt.num))[0])==null?void 0:O.file)??((ce=We.find(Nt=>Nt.file==="genesis.md"))==null?void 0:ce.file)??((ke=We.find(Nt=>Nt.file==="structure.md"))==null?void 0:ke.file)??((De=We[0])==null?void 0:De.file);Xe&&Se.current===oe&&o(Xe)}}catch{}},[t]),Ae=w.useCallback(oe=>{oe.preventDefault(),Dt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const O=ke=>{if(!Dt.current||!yt.current)return;const De=yt.current.getBoundingClientRect(),Ee=De.width-Pf-If,Pe=ke.clientX-De.left-Pf;I(jy(Pe/Ee,Ee))},ce=()=>{Dt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",ce)};window.addEventListener("mousemove",O),window.addEventListener("mouseup",ce)},[]),Ge=w.useCallback(async(oe,O,ce,ke,De,Ee)=>{var Xe;f(O),v("Reading file..."),N(null);let Pe=!1,We=null,rt=!1;try{const Nt=await t(`/api/stories/${oe}/${O}`);if(!Nt.ok)throw new Error("Failed to read file");const jt=await Nt.json(),Gt=He[oe];let Mt=null,Ni=null;if(O==="genesis.md")try{const ei=await t(`/api/stories/${oe}/structure.md`);ei.ok&&(Mt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${oe}/cuts/${O.replace(/\.md$/,"")}`);ei.ok&&(Ni=(await ei.json()).title??null)}catch{}const gr=Em({fileName:O,fileContent:jt.content,storySlug:oe,structureContent:Mt,contentType:Gt,episodeTitle:Ni});if(Gt==="cartoon"&&zo(gr,O))return v(O==="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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/)&&!km({fileContent:jt.content,episodeTitle:Ni}))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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O==="genesis.md"){const ei=Sm(jt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(O.match(/^plot-\d+\.md$/)){if(pM(jt)){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(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${oe}`);if(ei.ok){const Tn=(await ei.json()).files.find(or=>or.file==="genesis.md"&&or.storylineId);Jt=Tn==null?void 0:Tn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Dr=await ei.json();if(gM(Dr))return N(xM(Dr)),f(null),v(""),!1}}catch{}v("Publishing...");const Wi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:oe,fileName:O,title:gr,content:jt.content,genre:ce,language:ke,isNsfw:De,storylineId:Jt,...wy(He,oe,Jt)?{contentType:wy(He,oe,Jt)}:{}})});if(!Wi.ok){const ei=await Wi.json();throw new Error(ei.error||"Publish failed")}const qn=(Xe=Wi.body)==null?void 0:Xe.getReader(),xr=new TextDecoder;if(qn)for(;;){const{done:ei,value:Dr}=await qn.read();if(ei)break;const or=xr.decode(Dr).split(` +`).filter(on=>on.startsWith("data: "));for(const on of or)try{const St=JSON.parse(on.slice(6));if(St.step&&v(St.message||St.step),St.step==="done"&&St.txHash){if(rt=!0,await t(`/api/stories/${oe}/${O}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:St.txHash,storylineId:St.storylineId,plotIndex:St.plotIndex,contentCid:St.contentCid,gasCost:St.gasCost,indexError:St.indexError,authorAddress:M})}),x(An=>An+1),Ee&&O==="genesis.md"&&St.storylineId){v("Uploading cover...");let An=null;try{An=await uM(t,St.storylineId,Ee)}catch{}An||(Pe=!0)}if(Gt==="cartoon"&&St.storylineId)try{const An=O!=="genesis.md",Go=`storylineId=${St.storylineId}`+(An&&St.plotIndex!=null?`&plotIndex=${St.plotIndex}`:""),_r=await t(`/api/publish/public-title?${Go}`);if(_r.ok){const fi=await _r.json(),xn=An?{plots:fi.plotTitle!=null?[{plotIndex:St.plotIndex,title:fi.plotTitle}]:[]}:{title:fi.storylineTitle},Mi=WM({fileName:O,detail:xn,plotIndex:St.plotIndex});Mi.ok||(We=GM(Mi))}}catch{}}}catch{}}We&&N(We),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Nt){const jt=Nt instanceof Error?Nt.message:"Publish failed";v(`Error: ${jt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return rt&&!Pe},[t,He,M]),Fe=w.useCallback(oe=>{oe.startsWith("_new_")&&(q(O=>O.filter(ce=>ce!==oe)),je.current.delete(oe),$e.current.delete(oe),nt.current.delete(oe),Wt.current.delete(oe),re(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}),V(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}))},[]);w.useEffect(()=>{const oe=ce=>{_e(new Set(ce.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Le(new Set(ce.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const ke={},De={},Ee={},Pe={},We={},rt={};for(const Xe of ce)ke[Xe.name]=Xe.contentType||"fiction",De[Xe.name]=Xe.language,Ee[Xe.name]=Xe.genre,Pe[Xe.name]=Xe.isNsfw,We[Xe.name]=Xe.agentProvider,Xe.title&&(rt[Xe.name]=Xe.title);Ce(ke),et(De),Ke(Ee),ze(Pe),ki(We),Te(rt)};t("/api/stories").then(ce=>ce.ok?ce.json():null).then(ce=>{ce!=null&&ce.stories&&oe(ce.stories)}).catch(()=>{});const O=setInterval(async()=>{try{const ce=await t("/api/stories");if(ce.ok){const ke=await ce.json();oe(ke.stories)}}catch{}},5e3);return()=>clearInterval(O)},[t]);const dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",ft=!!T&&!dt,ct=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Kt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const oe=i;if((await t(`/api/stories/${oe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ki(ce=>({...ce,[oe]:"codex"})),V(ce=>({...ce,[oe]:"codex"}));try{const ce=await t("/api/stories");if(ce.ok){const ke=await ce.json();if(ke!=null&&ke.stories){const De={};for(const Ee of ke.stories)De[Ee.name]=Ee.agentProvider;ki(De)}}}catch{}}},[t,i]),Ei=w.useCallback(oe=>{i===oe&&(s(null),o(null))},[i]),pt=i?le[i]??Vt[i]:void 0,qi=Lf(i,He,je.current),jn=mM(qi,pt,i),sn=!!i&&qi==="cartoon",Fn=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",an=w.useCallback(oe=>{const O=i;if(O)switch(oe){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":H(O,"structure.md");break;case"genesis":H(O,"genesis.md");break;case"publish":h("publish");break}},[i,H]),gn=w.useCallback((oe,O)=>{const ce=i;if(ce)switch(oe){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":O&&H(ce,O);break}},[i,H]),ln=w.useCallback(oe=>{i&&(oe.genre!==void 0&&Ke(O=>({...O,[i]:oe.genre||void 0})),oe.language!==void 0&&et(O=>({...O,[i]:oe.language||void 0})),oe.isNsfw!==void 0&&ze(O=>({...O,[i]:oe.isNsfw})))},[i]),mr=w.useCallback(oe=>{tt(oe),xe(!oe)},[]),Ot=Ct&&!Q;return d.jsxs("div",{ref:yt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Ot?"stories-focused-lettering-mode":"stories-default-layout",children:[!Ot&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:H,onNewStory:Qe,untitledSessions:te})}),!Ot&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${j} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Oe,onDestroySession:Fe,onArchiveStory:Ei,confirmedStories:he,renameRef:Lt,bypassStories:X,agentProviders:le,readiness:T,contentType:Lf(i,He,je.current),needsProviderRepair:jn,onRepairProvider:Kt})}),!Ot&&d.jsx("div",{onMouseDown:Ae,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:If,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Ot?{flex:"1 0 0"}:{flex:`${1-j} 0 0`},children:[!Ct&&sn&&i&&d.jsx(HM,{storyTitle:_t[i]||i,active:Fn,onSelect:an}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:sn&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:ln}):sn&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:H}):sn&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:at[i],language:Ue[i],isNsfw:Et[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:H}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:M,contentType:Lf(i,He,je.current)||"fiction",language:i?Ue[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?Et[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:oe=>i&&H(i,oe),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:mr,onFocusedLetteringWorkspaceVisibleChange:xe})}),!Ct&&sn&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:gn,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:oe=>be(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:oe=>ne(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:oe=>G(oe.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:[d.jsx("option",{value:"",children:"— Select later —"}),sl.map(oe=>d.jsx("option",{value:oe,children:oe},oe))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:Y,onChange:oe=>U(oe.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:ts.map(oe=>d.jsx("option",{value:oe,children:oe},oe))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:A,onChange:oe=>z(oe.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:oe=>ge(oe.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>di("fiction",Y,A,$),disabled:!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>di("cartoon",Y,A,"codex"),disabled:ft||!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),wu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:$p}),T&&T.codex.installed&&!wu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:ct,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:K?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{Op as M,ko as a,$S as b,$D as c,$3 as d,Co as l,vm as s,YS as t,n4 as v}; diff --git a/app/web/dist/assets/index-Bi-xodT8.css b/app/web/dist/assets/index-Bi-xodT8.css deleted file mode 100644 index 18b935c..0000000 --- a/app/web/dist/assets/index-Bi-xodT8.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-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-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-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.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-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.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}.justify-end{justify-content:flex-end}.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-\[\#f8f5ef\]{background-color:#f8f5ef}.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\/35{background-color:#f0ebe159}.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-surface\/95{background-color:#f0ebe1f2}.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/index.html b/app/web/dist/index.html index 44e4479..2f6feda 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,8 +7,8 @@ - - + +
From 9997a1b0ad2d7e9218f53e39a7c7fc56aac6fdf1 Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:13:17 +0000 Subject: [PATCH 2/4] Restore cartoon CTA workflow actions --- app/web/components/PreviewPanel.test.tsx | 56 ++++++ app/web/components/PreviewPanel.tsx | 35 ++++ app/web/components/StoriesPage.test.tsx | 160 ++++++++++++++++++ app/web/components/StoriesPage.tsx | 20 ++- ...cut-BuLQ0Lx7.js => export-cut-m_bbvXgX.js} | 2 +- app/web/dist/assets/index-BLc-rD_a.js | 141 --------------- app/web/dist/assets/index-OmkX9BzW.js | 141 +++++++++++++++ app/web/dist/index.html | 2 +- 8 files changed, 413 insertions(+), 144 deletions(-) rename app/web/dist/assets/{export-cut-BuLQ0Lx7.js => export-cut-m_bbvXgX.js} (98%) delete mode 100644 app/web/dist/assets/index-BLc-rD_a.js create mode 100644 app/web/dist/assets/index-OmkX9BzW.js diff --git a/app/web/components/PreviewPanel.test.tsx b/app/web/components/PreviewPanel.test.tsx index 2d1fdbf..0f5f6c6 100644 --- a/app/web/components/PreviewPanel.test.tsx +++ b/app/web/components/PreviewPanel.test.tsx @@ -51,6 +51,27 @@ function makeAuthFetch() { }); } +function makeGenerateMarkdownAuthFetch() { + const calls: string[] = []; + const fn = vi.fn((url: string) => { + calls.push(url); + if (url.includes("/asset/")) { + return Promise.resolve({ ok: true, status: 200, blob: () => Promise.resolve(new Blob(["x"], { type: "image/webp" })) }); + } + let data: unknown = {}; + if (url.includes("/progress")) data = { contentType: "cartoon", coach: genesisCoach }; + else if (url.includes("/cuts/genesis/generate-markdown")) data = { ok: true }; + else if (url.includes("/cuts/genesis/detect-clean-images")) data = { detected: [], stale: [] }; + else if (url.includes("/cuts/genesis/asset-diagnostics")) data = { diagnostics: [], summary: {} }; + else if (url.includes("/cuts/genesis")) data = { version: 1, plotFile: "genesis", cuts: [genesisCut] }; + else if (url.includes("/cover-asset")) data = { found: false }; + else if (url.endsWith("/genesis.md")) data = { file: "genesis.md", status: "pending", content: "# Opening\n\nThe story begins." }; + else if (url.endsWith("/structure.md")) data = { content: "# Bible" }; + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(data) }); + }); + return { fn, calls }; +} + describe("PreviewPanel — cartoon file chrome", () => { it("does not render the old top workflow coach in cartoon file views (#498)", async () => { render(); @@ -106,4 +127,39 @@ describe("PreviewPanel — cartoon file chrome", () => { expect(await screen.findByText("The story begins.")).toBeInTheDocument(); } }); + + it("applies an open-lettering workflow request by landing in Genesis cuts edit", async () => { + render( + , + ); + + expect(await screen.findByTestId("cut-list-panel")).toBeInTheDocument(); + expect(screen.getByTestId("genesis-edit-mode-cuts")).toBeInTheDocument(); + }); + + it("applies a generate-markdown workflow request through the generation endpoint", async () => { + const { fn, calls } = makeGenerateMarkdownAuthFetch(); + render( + , + ); + + await screen.findByText("The story begins."); + expect( + calls.some((url) => url.includes("/cuts/genesis/generate-markdown")), + ).toBe(true); + }); }); diff --git a/app/web/components/PreviewPanel.tsx b/app/web/components/PreviewPanel.tsx index 4ae033b..f29c688 100644 --- a/app/web/components/PreviewPanel.tsx +++ b/app/web/components/PreviewPanel.tsx @@ -4,6 +4,7 @@ import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; import { GENRES, LANGUAGES, canonicalizeGenre } from "../../../lib/genres"; +import type { CoachUiAction } from "@app-lib/cartoon-coach"; import { CartoonPreview } from "./CartoonPreview"; import { CartoonPublishPreview } from "./CartoonPublishPreview"; import { CutListPanel } from "./CutListPanel"; @@ -118,6 +119,11 @@ interface PreviewPanelProps { onFocusedLetteringModeChange?: (active: boolean) => void; /** Restore/fold the wider app work area while staying in the editor. */ onFocusedLetteringWorkspaceVisibleChange?: (visible: boolean) => void; + workflowActionRequest?: { + action: CoachUiAction; + seq: number; + } | null; + onWorkflowActionHandled?: (seq: number) => void; } interface FileData { @@ -153,6 +159,8 @@ export function PreviewPanel({ focusedLetteringWorkspaceVisible = false, onFocusedLetteringModeChange, onFocusedLetteringWorkspaceVisibleChange, + workflowActionRequest = null, + onWorkflowActionHandled, }: PreviewPanelProps) { const [fileData, setFileData] = useState(null); const [loading, setLoading] = useState(false); @@ -267,6 +275,7 @@ export function PreviewPanel({ const illustrationInputRef = useRef(null); const prevFileRef = useRef(null); + const appliedWorkflowSeqRef = useRef(0); const loadFile = useCallback(async () => { if (!storyName || !fileName) { @@ -531,6 +540,32 @@ export function PreviewPanel({ } }, [storyName, fileName, authFetch, loadFile]); + useEffect(() => { + if (!workflowActionRequest) return; + if (workflowActionRequest.seq === appliedWorkflowSeqRef.current) return; + appliedWorkflowSeqRef.current = workflowActionRequest.seq; + + switch (workflowActionRequest.action) { + case "view-progress": + onViewProgress?.(); + break; + case "open-cuts": + case "open-lettering": + case "upload": + case "refresh-assets": + setActiveTab("edit"); + setGenesisEditMode("cuts"); + break; + case "generate-markdown": + handleGenerateMarkdown(); + break; + case "publish": + setActiveTab("preview"); + break; + } + onWorkflowActionHandled?.(workflowActionRequest.seq); + }, [workflowActionRequest, onViewProgress, handleGenerateMarkdown, onWorkflowActionHandled]); + // Handle cover image selection const handleCoverSelect = useCallback( (e: React.ChangeEvent) => { diff --git a/app/web/components/StoriesPage.test.tsx b/app/web/components/StoriesPage.test.tsx index e5ec852..b56f612 100644 --- a/app/web/components/StoriesPage.test.tsx +++ b/app/web/components/StoriesPage.test.tsx @@ -30,6 +30,9 @@ const childProps = vi.hoisted(() => ({ }>, previewStory: undefined as string | null | undefined, previewFile: undefined as string | null | undefined, + workflowActionRequest: null as + | null + | { action: string; seq: number }, })); vi.mock("./StoryBrowser", () => ({ @@ -84,14 +87,18 @@ vi.mock("./PreviewPanel", () => ({ fileName?: string | null; onFocusedLetteringModeChange?: (active: boolean) => void; onFocusedLetteringWorkspaceVisibleChange?: (visible: boolean) => void; + workflowActionRequest?: { action: string; seq: number } | null; + onWorkflowActionHandled?: (seq: number) => void; }) => { childProps.previewStory = props.storyName; childProps.previewFile = props.fileName; + childProps.workflowActionRequest = props.workflowActionRequest ?? null; return (
+
); }, @@ -145,6 +161,7 @@ afterEach(() => { childProps.renameCalls = []; childProps.previewStory = undefined; childProps.previewFile = undefined; + childProps.workflowActionRequest = null; }); interface FetchCall { @@ -794,6 +811,110 @@ function makeTwoCartoonAuthFetch() { return { fn }; } +function makeWorkflowActionAuthFetch(coachAction: "open-lettering" | "generate-markdown") { + const stories = [ + { + name: "cartoon-a", + title: "Story A", + 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: "present", + episodes: [ + { + file: "genesis.md", + label: "Episode 1 / Genesis", + kind: "genesis", + title: "Opening", + state: "in-progress", + summary: "Needs action", + published: false, + checklist: [], + cuts: { + total: 1, + needClean: 0, + withClean: 1, + withText: 0, + exported: 0, + uploaded: 0, + }, + }, + ], + summary: { + episodes: 1, + published: 0, + readyToPublish: 0, + placeholders: 0, + blocked: 1, + }, + nextAction: "Review cuts and start lettering.", + nextPrompt: null, + coach: { + stageLabel: "Clean images ready", + action: + coachAction === "generate-markdown" + ? "Prepare the episode for publish" + : "Review cuts and start lettering", + actionKind: "ui", + prompt: null, + uiAction: coachAction, + episodeFile: "genesis.md", + }, + }; + 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.includes("/progress")) + return Promise.resolve({ + ok: true, + json: () => Promise.resolve(progress), + }); + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ contentType: "cartoon", files: [] }), + }); + }); + return { fn }; +} + describe("StoriesPage cartoon workflow nav routing (#439)", () => { it("routes file-backed nav tabs to the CURRENT story after a left-tree switch to another story (#445 RE1)", async () => { const { fn } = makeTwoCartoonAuthFetch(); @@ -902,4 +1023,43 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { ); expect(within(cta).getByRole("button", { name: "Next Action" })).toBeInTheDocument(); }, 10000); + + it("passes open-lettering through to PreviewPanel as a one-shot workflow action request", async () => { + const { fn } = makeWorkflowActionAuthFetch("open-lettering"); + render(); + await waitFor(() => expect(childProps.onSelectFile).not.toBeNull()); + + childProps.onSelectFile!("cartoon-a", "genesis.md"); + await waitFor(() => expect(childProps.previewFile).toBe("genesis.md")); + + const cta = await screen.findByTestId("workflow-persistent-next-action"); + fireEvent.click(within(cta).getByRole("button", { name: "Next Action" })); + + await waitFor(() => + expect(childProps.workflowActionRequest).toMatchObject({ + action: "open-lettering", + }), + ); + + fireEvent.click(screen.getByTestId("mock-handle-workflow-action")); + await waitFor(() => expect(childProps.workflowActionRequest).toBeNull()); + }, 10000); + + it("passes generate-markdown through to PreviewPanel instead of dropping it at file selection", async () => { + const { fn } = makeWorkflowActionAuthFetch("generate-markdown"); + render(); + await waitFor(() => expect(childProps.onSelectFile).not.toBeNull()); + + childProps.onSelectFile!("cartoon-a", "genesis.md"); + await waitFor(() => expect(childProps.previewFile).toBe("genesis.md")); + + const cta = await screen.findByTestId("workflow-persistent-next-action"); + fireEvent.click(within(cta).getByRole("button", { name: "Next Action" })); + + await waitFor(() => + expect(childProps.workflowActionRequest).toMatchObject({ + action: "generate-markdown", + }), + ); + }, 10000); }); diff --git a/app/web/components/StoriesPage.tsx b/app/web/components/StoriesPage.tsx index 412306f..593cdf7 100644 --- a/app/web/components/StoriesPage.tsx +++ b/app/web/components/StoriesPage.tsx @@ -143,6 +143,10 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { focusedLetteringWorkspaceVisible, setFocusedLetteringWorkspaceVisible, ] = useState(true); + const [workflowActionRequest, setWorkflowActionRequest] = useState<{ + action: CoachUiAction; + seq: number; + } | null>(null); const contentTypeMap = useRef>(new Map()); const languageMap = useRef>(new Map()); const agentModeMap = useRef>(new Map()); @@ -1064,6 +1068,12 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { (action: CoachUiAction, episodeFile: string | null) => { const story = selectedStory; if (!story) return; + const queueWorkflowAction = (nextAction: CoachUiAction) => { + setWorkflowActionRequest((prev) => ({ + action: nextAction, + seq: (prev?.seq ?? 0) + 1, + })); + }; switch (action) { case "view-progress": setCartoonView(null); @@ -1077,7 +1087,9 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { case "upload": case "refresh-assets": case "generate-markdown": - if (episodeFile) handleSelectFile(story, episodeFile); + if (!episodeFile) return; + handleSelectFile(story, episodeFile); + queueWorkflowAction(action); break; } }, @@ -1275,6 +1287,12 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { onFocusedLetteringWorkspaceVisibleChange={ setFocusedLetteringWorkspaceVisible } + workflowActionRequest={workflowActionRequest} + onWorkflowActionHandled={(seq) => + setWorkflowActionRequest((prev) => + prev?.seq === seq ? null : prev, + ) + } /> )}
diff --git a/app/web/dist/assets/export-cut-BuLQ0Lx7.js b/app/web/dist/assets/export-cut-m_bbvXgX.js similarity index 98% rename from app/web/dist/assets/export-cut-BuLQ0Lx7.js rename to app/web/dist/assets/export-cut-m_bbvXgX.js index 44c5a78..d10de7c 100644 --- a/app/web/dist/assets/export-cut-BuLQ0Lx7.js +++ b/app/web/dist/assets/export-cut-m_bbvXgX.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-BLc-rD_a.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-OmkX9BzW.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-BLc-rD_a.js b/app/web/dist/assets/index-BLc-rD_a.js deleted file mode 100644 index 3c89a1d..0000000 --- a/app/web/dist/assets/index-BLc-rD_a.js +++ /dev/null @@ -1,141 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Lu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yd={exports:{}},so={};/** - * @license React - * react-jsx-runtime.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ib;function pC(){if(ib)return so;ib=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 so.Fragment=t,so.jsx=i,so.jsxs=i,so}var nb;function mC(){return nb||(nb=1,Yd.exports=pC()),Yd.exports}var d=mC(),Vd={exports:{}},it={};/** - * @license React - * react.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var rb;function gC(){if(rb)return it;rb=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"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,M={};function E(D,K,C){this.props=D,this.context=K,this.refs=M,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,K){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,K,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function j(){}j.prototype=E.prototype;function I(D,K,C){this.props=D,this.context=K,this.refs=M,this.updater=C||S}var te=I.prototype=new j;te.constructor=I,N(te,E.prototype),te.isPureReactComponent=!0;var q=Array.isArray;function R(){}var ie={H:null,A:null,T:null,S:null},fe=Object.prototype.hasOwnProperty;function be(D,K,C){var X=C.ref;return{$$typeof:e,type:D,key:K,ref:X!==void 0?X:null,props:C}}function B(D,K){return be(D.type,K,D.props)}function ne(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function F(D){var K={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(C){return K[C]})}var G=/\/+/g;function Y(D,K){return typeof D=="object"&&D!==null&&D.key!=null?F(""+D.key):K.toString(36)}function U(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(R,R):(D.status="pending",D.then(function(K){D.status==="pending"&&(D.status="fulfilled",D.value=K)},function(K){D.status==="pending"&&(D.status="rejected",D.reason=K)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function A(D,K,C,X,re){var le=typeof D;(le==="undefined"||le==="boolean")&&(D=null);var V=!1;if(D===null)V=!0;else switch(le){case"bigint":case"string":case"number":V=!0;break;case"object":switch(D.$$typeof){case e:case t:V=!0;break;case _:return V=D._init,A(V(D._payload),K,C,X,re)}}if(V)return re=re(D),V=X===""?"."+Y(D,0):X,q(re)?(C="",V!=null&&(C=V.replace(G,"$&/")+"/"),A(re,K,C,"",function(Me){return Me})):re!=null&&(ne(re)&&(re=B(re,C+(re.key==null||D&&D.key===re.key?"":(""+re.key).replace(G,"$&/")+"/")+V)),K.push(re)),1;V=0;var he=X===""?".":X+":";if(q(D))for(var _e=0;_e>>1,T=A[ge];if(0>>1;gea(C,$))Xa(re,C)?(A[ge]=re,A[X]=$,ge=X):(A[ge]=C,A[K]=$,ge=K);else if(Xa(re,$))A[ge]=re,A[X]=$,ge=X;else break e}}return z}function a(A,z){var $=A.sortIndex-z.sortIndex;return $!==0?$:A.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=A)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(A){if(N=!1,te(A),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(q,z.startTime-A)}}var R=!1,ie=-1,fe=5,be=-1;function B(){return M?!0:!(e.unstable_now()-beA&&B());){var ge=x.callback;if(typeof ge=="function"){x.callback=null,b=x.priorityLevel;var T=ge(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),z=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&U(q,D.startTime-A),z=!1}}break e}finally{x=null,b=$,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof I=="function")F=function(){I(ne)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,Y=G.port2;G.port1.onmessage=ne,F=function(){Y.postMessage(null)}}else F=function(){E(ne,0)};function U(A,z){ie=E(function(){A(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(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125ge?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(N?(j(ie),ie=-1):N=!0,U(q,$-ge))):(A.sortIndex=T,t(p,A),S||v||(S=!0,R||(R=!0,F()))),A},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(A){var z=b;return function(){var $=b;b=z;try{return A.apply(this,arguments)}finally{b=$}}}})(Zd)),Zd}var lb;function bC(){return lb||(lb=1,Xd.exports=_C()),Xd.exports}var Qd={exports:{}},Ji={};/** - * @license React - * react-dom.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ob;function vC(){if(ob)return Ji;ob=1;var e=Up();function t(p){var f="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(),Qd.exports=vC(),Qd.exports}/** - * @license React - * react-dom-client.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ub;function SC(){if(ub)return ao;ub=1;var e=bC(),t=Up(),i=yC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=ge[T],ge[T]=null,T--)}function C(n,r){T++,ge[T]=n.current,n.current=r}var X=D(null),re=D(null),le=D(null),V=D(null);function he(n,r){switch(C(le,r),C(re,n),C(X,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}K(X),C(X,n)}function _e(){K(X),K(re),K(le)}function Me(n){n.memoizedState!==null&&C(V,n);var r=X.current,l=E_(r,n.type);r!==l&&(C(re,n),C(X,l))}function Le(n){re.current===n&&(K(X),K(re)),V.current===n&&(K(V),to._currentValue=$)}var He,Ce;function Ue(n){if(He===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);He=r&&r[1]||"",Ce=-1)":-1m||L[u]!==J[m]){var ue=` -`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{et=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ue(l):""}function Ke(n,r){switch(n.tag){case 26:case 27:case 5:return Ue(n.type);case 16:return Ue("Lazy");case 13:return n.child!==r&&r!==null?Ue("Suspense Fallback"):Ue("Suspense");case 19:return Ue("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return Ue("Activity");default:return""}}function Et(n){try{var r="",l=null;do r+=Ke(n,l),l=n,n=n.return;while(n);return r}catch(u){return` -Error generating stack: `+u.message+` -`+u.stack}}var ze=Object.prototype.hasOwnProperty,_t=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Vt=e.unstable_shouldYield,ki=e.unstable_requestPaint,Ct=e.unstable_now,tt=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,je=e.unstable_NormalPriority,$e=e.unstable_LowPriority,nt=e.unstable_IdlePriority,Wt=e.log,hi=e.unstable_setDisableYieldValue,Lt=null,yt=null;function Dt(n){if(typeof Wt=="function"&&hi(n),yt&&typeof yt.setStrictMode=="function")try{yt.setStrictMode(Lt,n)}catch{}}var Qe=Math.clz32?Math.clz32:Se,di=Math.log,H=Math.LN2;function Se(n){return n>>>=0,n===0?32:31-(di(n)/H|0)|0}var Oe=256,Ae=262144,Ge=4194304;function Fe(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Fe(u):(y&=k,y!==0?m=Fe(y):l||(l=k&~n,l!==0&&(m=Fe(l))))):(k=u&~g,k!==0?m=Fe(k):y!==0?m=Fe(y):l||(l=u&~n,l!==0&&(m=Fe(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 ft(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function ct(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 Kt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ei(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function pt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function qi(n,r,l,u,m,g){var y=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,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Mi=/[\n"\\]/g;function ni(n){return n.replace(Mi,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Mr(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+St(r)):n.value!==""+St(r)&&(n.value=""+St(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?xa(n,y,St(r)):l!=null?xa(n,y,St(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=""+St(k):n.removeAttribute("name")}function Br(n,r,l,u,m,g,y,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)){_r(n);return}l=l!=null?""+St(l):"",r=r!=null?""+St(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),_r(n)}function xa(n,r,l){r==="number"&&xn(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Lr(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"),Ne=!1;if(ye)try{var Je={};Object.defineProperty(Je,"passive",{get:function(){Ne=!0}}),window.addEventListener("test",Je,Je),window.removeEventListener("test",Je,Je)}catch{Ne=!1}var Tt=null,xi=null,Yn=null;function Or(){if(Yn)return Yn;var n,r=xi,l=r.length,u,m="value"in Tt?Tt.value:Tt.textContent,g=m.length;for(n=0;n=Sl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var va=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(va)return n==="compositionend"||!Ju&&Bm(n,r)?(n=Or(),Yn=xi=Tt=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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xn(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=xn(n.document)}return r}function ih(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 Y1=ye&&"documentMode"in document&&11>=document.documentMode,ya=null,nh=null,El=null,rh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;rh||ya==null||ya!==xn(u)||(u=ya,"selectionStart"in u&&ih(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}),El&&kl(El,u)||(El=u,u=Pc(nh,"onSelect"),0>=y,m-=y,br=1<<32-Qe(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var Rt=ee(W,Ie,Z[lt],de);if(Rt===null){Ie===null&&(Ie=vt);break}n&&Ie&&Rt.alternate===null&&r(W,Ie),P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt,Ie=vt}if(lt===Z.length)return l(W,Ie),wt&&Pr(W,lt),qe;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Ts=ee(W,Ie,Rt.value,de);if(Ts===null){Ie===null&&(Ie=vt);break}n&&Ie&&Ts.alternate===null&&r(W,Ie),P=g(Ts,P,lt),At===null?qe=Ts:At.sibling=Ts,At=Ts,Ie=vt}if(Rt.done)return l(W,Ie),wt&&Pr(W,lt),qe;if(Ie===null){for(;!Rt.done;lt++,Rt=Z.next())Rt=pe(W,Rt.value,de),Rt!==null&&(P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt);return wt&&Pr(W,lt),qe}for(Ie=u(Ie);!Rt.done;lt++,Rt=Z.next())Rt=ae(Ie,W,lt,Rt.value,de),Rt!==null&&(n&&Rt.alternate!==null&&Ie.delete(Rt.key===null?lt:Rt.key),P=g(Rt,P,lt),At===null?qe=Rt:At.sibling=Rt,At=Rt);return n&&Ie.forEach(function(fC){return r(W,fC)}),wt&&Pr(W,lt),qe}function Ut(W,P,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===N&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var qe=Z.key;P!==null;){if(P.key===qe){if(qe=Z.type,qe===N){if(P.tag===7){l(W,P.sibling),de=m(P,Z.props.children),de.return=W,W=de;break e}}else if(P.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===fe&&Zs(qe)===P.type){l(W,P.sibling),de=m(P,Z.props),Dl(de,Z),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Z.type===N?(de=Gs(Z.props.children,W.mode,de,Z.key),de.return=W,W=de):(de=tc(Z.type,Z.key,Z.props,null,W.mode,de),Dl(de,Z),de.return=W,W=de)}return y(W);case S:e:{for(qe=Z.key;P!==null;){if(P.key===qe)if(P.tag===4&&P.stateNode.containerInfo===Z.containerInfo&&P.stateNode.implementation===Z.implementation){l(W,P.sibling),de=m(P,Z.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=hh(Z,W.mode,de),de.return=W,W=de}return y(W);case fe:return Z=Zs(Z),Ut(W,P,Z,de)}if(U(Z))return Be(W,P,Z,de);if(F(Z)){if(qe=F(Z),typeof qe!="function")throw Error(s(150));return Z=qe.call(Z),Ve(W,P,Z,de)}if(typeof Z.then=="function")return Ut(W,P,oc(Z),de);if(Z.$$typeof===I)return Ut(W,P,rc(W,Z),de);cc(W,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Z),de.return=W,W=de):(l(W,P),de=uh(Z,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Z,de){try{Rl=0;var qe=Ut(W,P,Z,de);return Da=null,qe}catch(Ie){if(Ie===Ra||Ie===ac)throw Ie;var At=Mn(29,Ie,null,W.mode);return At.lanes=de,At.return=W,At}finally{}}}var Js=gg(!0),xg=gg(!1),ds=!1;function wh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ch(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 fs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ps(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Bt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=ec(n),eg(n,null,l),r}return Jo(n,u,r,l),ec(n)}function Ml(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,sn(n,l)}}function kh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Eh=!1;function Bl(){if(Eh){var n=Aa;if(n!==null)throw n}}function Ll(n,r,l,u){Eh=!1;var m=n.updateQueue;ds=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=J=L=null,k=g;do{var ee=k.lane&-536870913,ae=ee!==k.lane;if(ae?(bt&ee)===ee:(u&ee)===ee){ee!==0&&ee===Ta&&(Eh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Be=n,Ve=k;ee=r;var Ut=l;switch(Ve.tag){case 1:if(Be=Ve.payload,typeof Be=="function"){pe=Be.call(Ut,pe,ee);break e}pe=Be;break e;case 3:Be.flags=Be.flags&-65537|128;case 0:if(Be=Ve.payload,ee=typeof Be=="function"?Be.call(Ut,pe,ee):Be,ee==null)break e;pe=x({},pe,ee);break e;case 2:ds=!0}}ee=k.callback,ee!==null&&(n.flags|=64,ae&&(n.flags|=8192),ae=m.callbacks,ae===null?m.callbacks=[ee]:ae.push(ee))}else ae={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=ae,L=pe):ue=ue.next=ae,y|=ee;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ae=k,k=ae.next,ae.next=null,m.lastBaseUpdate=ae,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),bs|=y,n.lanes=y,n.memoizedState=pe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Wh(n,!1,r,l);try{var L=m(),J=A.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=iw(L,u);Pl(n,r,ue,Pn(n))}else Pl(n,r,u,Pn(n))}catch(pe){Pl(n,r,{then:function(){},status:"rejected",reason:pe},Pn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function ow(){}function Fh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,$,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Pl(n,r.next.queue,{},Pn())}function qh(){return Yi(to)}function Jg(){return mi().memoizedState}function ex(){return mi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Pn();n=fs(l);var u=ps(r,n,l);u!==null&&(wn(u,r,l),Ml(u,r,l)),r={cache:bh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Pn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},bc(n)?ix(r,l):(l=oh(n,r,l,u),l!==null&&(wn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Pn();Pl(n,r,l,u)}function Pl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(bc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Dn(k,y))return Jo(n,r,m,0),Ft===null&&Qo(),!1}catch{}finally{}if(l=oh(n,r,m,u),l!==null)return wn(l,n,u),nx(l,r,u),!0}return!1}function Wh(n,r,l,u){if(u={lane:2,revertLane:wd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},bc(n)){if(r)throw Error(s(479))}else r=oh(n,l,u,2),r!==null&&wn(r,n,2)}function bc(n){var r=n.alternate;return n===st||r!==null&&r===st}function ix(n,r){Ba=dc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,sn(n,l)}}var Il={readContext:Yi,use:mc,useCallback:ai,useContext:ai,useEffect:ai,useImperativeHandle:ai,useLayoutEffect:ai,useInsertionEffect:ai,useMemo:ai,useReducer:ai,useRef:ai,useState:ai,useDebugValue:ai,useDeferredValue:ai,useTransition:ai,useSyncExternalStore:ai,useId:ai,useHostTransitionStatus:ai,useFormState:ai,useActionState:ai,useOptimistic:ai,useMemoCache:ai,useCacheRefresh:ai};Il.useEffectEvent=ai;var rx={readContext:Yi,use:mc,useCallback:function(n,r){return cn().memoizedState=[n,r===void 0?null:r],n},useContext:Yi,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,xc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return xc(4194308,4,n,r)},useInsertionEffect:function(n,r){xc(4,2,n,r)},useMemo:function(n,r){var l=cn();r=r===void 0?null:r;var u=n();if(ea){Dt(!0);try{n()}finally{Dt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=cn();if(l!==void 0){var m=l(r);if(ea){Dt(!0);try{l(r)}finally{Dt(!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=uw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=cn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ph(n);var r=n.queue,l=tx.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Uh,useDeferredValue:function(n,r){var l=cn();return $h(l,n,r)},useTransition:function(){var n=Ph(!1);return n=Xg.bind(null,st,n.queue,!0,!1),cn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=cn();if(wt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(bt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Oa(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=cn(),r=Ft.identifierPrefix;if(wt){var l=vr,u=br;l=(u&~(1<<32-Qe(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=fc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[oe]=r,g[O]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Ki(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&&qr(r)}}return Zt(r),sd(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=le.current,Na(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Gi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[oe]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||us(r,!0)}else n=Ic(n).createTextNode(u),n[oe]=r,r.stateNode=n}return Zt(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[oe]=r}else Ys(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=mh(),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 Zt(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[oe]=r}else Ys(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=mh(),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),Cc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&Nd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(K(pi),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Ul(u,!1);else{if(li!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=hc(n),g!==null){for(r.flags|=128,Ul(u,!1),n=g.updateQueue,r.updateQueue=n,Cc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(pi,pi.current&1|2),wt&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Tc&&(r.flags|=128,m=!0,Ul(u,!1),r.lanes=4194304)}else{if(!m)if(n=hc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Cc(r,n),Ul(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!wt)return Zt(r),null}else 2*Ct()-u.renderingStartTime>Tc&&l!==536870912&&(r.flags|=128,m=!0,Ul(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=Ct(),n.sibling=null,l=pi.current,C(pi,m?l&1|2:l&1),wt&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Ln(r),jh(),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&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&Cc(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&&K(Xs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(_i),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(fh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(_i),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Ln(r),r.alternate===null)throw Error(s(340));Ys()}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));Ys()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return K(pi),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Ln(r),jh(),n!==null&&K(Xs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(_i),null;case 25:return null;default:return null}}function jx(n,r){switch(fh(r),r.tag){case 3:Hr(_i),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Ln(r);break;case 13:Ln(r);break;case 19:K(pi);break;case 10:Hr(r.type);break;case 22:case 23:Ln(r),jh(),n!==null&&K(Xs);break;case 24:Hr(_i)}}function $l(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Pt(r,r.return,k)}}function xs(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ue){Pt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){Pt(r,r.return,ue)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Pt(n,n.return,u)}}}function Ax(n,r,l){l.props=ta(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Pt(n,r,u)}}function Fl(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){Pt(n,r,m)}}function yr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Pt(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){Pt(n,r,m)}else l.current=null}function Rx(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){Pt(n,n.return,m)}}function ad(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[O]=r}catch(m){Pt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Cs(n.type)||n.tag===4}function ld(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&Cs(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 od(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=Rn));else if(u!==4&&(u===27&&Cs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(od(n,r,l),n=n.sibling;n!==null;)od(n,r,l),n=n.sibling}function kc(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&&Cs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(kc(n,r,l),n=n.sibling;n!==null;)kc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Ki(r,u,l),r[oe]=n,r[O]=l}catch(g){Pt(n,n.return,g)}}var Wr=!1,yi=!1,cd=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Bi=null;function gw(n,r){if(n=n.containerInfo,Ad=Gc,n=Gm(n),ih(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 y=0,k=-1,L=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var ae;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(ae=pe.firstChild)!==null;)ee=pe,pe=ae;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(L=y),(ae=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=ae}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Rd={focusedElem:n,selectionRange:l},Gc=!1,Bi=r;Bi!==null;)if(r=Bi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Bi=n;else for(;Bi!==null;){switch(r=Bi,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"))),Ki(g,u,l),g[oe]=n,Mt(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Ut);if(W&&P&&(ae.rangeCount!==1||ae.anchorNode!==W.node||ae.anchorOffset!==W.offset||ae.focusNode!==P.node||ae.focusOffset!==P.offset)){var Z=pe.createRange();Z.setStart(W.node,W.offset),ae.removeAllRanges(),Ve>Ut?(ae.addRange(Z),ae.extend(P.node,P.offset)):(Z.setEnd(P.node,P.offset),ae.addRange(Z))}}}}for(pe=[],ae=k;ae=ae.parentNode;)ae.nodeType===1&&pe.push({element:ae,left:ae.scrollLeft,top:ae.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=gd,gd=null;var g=ys,y=Xr;if(ji=0,Ua=ys=null,Xr=0,(Bt&6)!==0)throw Error(s(331));var k=Bt;if(Bt|=4,Wx(g.current),$x(g,g.current,y,l),Bt=k,Kl(0,!1),yt&&typeof yt.onPostCommitFiberRoot=="function")try{yt.onPostCommitFiberRoot(Lt,g)}catch{}return!0}finally{z.p=m,A.T=u,c_(n,r)}}function h_(n,r,l){r=Xn(l,r),r=Kh(n.stateNode,r,2),n=ps(n,r,2),n!==null&&(pt(n,2),Sr(n))}function Pt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(vs===null||!vs.has(u))){n=Xn(l,n),l=dx(2),u=ps(r,l,2),u!==null&&(fx(l,u,r,n),pt(u,2),Sr(u));break}}r=r.return}}function vd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(dd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(bt&l)===l&&(li===4||li===3&&(bt&62914560)===bt&&300>Ct()-jc?(Bt&2)===0&&$a(n,0):fd|=l,Ha===bt&&(Ha=0)),Sr(n)}function d_(n,r){r===0&&(r=Kt()),n=Ws(n,r),n!==null&&(pt(n,r),Sr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return _t(n,r)}var Lc=null,qa=null,yd=!1,Oc=!1,Sd=!1,ws=0;function Sr(n){n!==qa&&n.next===null&&(qa===null?Lc=qa=n:qa=qa.next=n),Oc=!0,yd||(yd=!0,Tw())}function Kl(n,r){if(!Sd&&Oc){Sd=!0;do for(var l=!1,u=Lc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Qe(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=bt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||ft(u,g)||(l=!0,g_(u,g));u=u.next}while(l);Sd=!1}}function jw(){f_()}function f_(){Oc=yd=!1;var n=0;ws!==0&&Iw()&&(n=ws);for(var r=Ct(),l=null,u=Lc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Lc=m:l.next=m,m===null&&(qa=l)):(l=u,(n!==0||(g&3)!==0)&&(Oc=!0)),u=m}ji!==0&&ji!==5||Kl(n),ws!==0&&(ws=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&C_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function O_(n,r,l){var u=Wa;if(u&&typeof r=="string"&&r){var m=ni(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Ki(r,"link",n),Mt(r),u.head.appendChild(r)))}}function Vw(n){Zr.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){Zr.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){Zr.L(n,r,l);var u=Wa;if(u&&n&&r){var m='link[rel="preload"][as="'+ni(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+ni(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+ni(l.imageSizes)+'"]')):m+='[href="'+ni(n)+'"]';var g=m;switch(r){case"style":g=Ga(n);break;case"script":g=Ya(n)}ir.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),ir.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(Jl(g))||r==="script"&&u.querySelector(eo(g))||(r=u.createElement("link"),Ki(r,"link",n),Mt(r),u.head.appendChild(r)))}}function Zw(n,r){Zr.m(n,r);var l=Wa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+ni(u)+'"][href="'+ni(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ya(n)}if(!ir.has(g)&&(n=x({rel:"modulepreload",href:n},r),ir.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(eo(g)))return}u=l.createElement("link"),Ki(u,"link",n),Mt(u),l.head.appendChild(u)}}}function Qw(n,r,l){Zr.S(n,r,l);var u=Wa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ga(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(Jl(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=ir.get(g))&&Pd(n,l);var L=y=u.createElement("link");Mt(L),Ki(L,"link",n),L._p=new Promise(function(J,ue){L.onload=J,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Uc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){Zr.X(n,r);var l=Wa;if(l&&n){var u=Gt(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(eo(m)),g||(n=x({src:n,async:!0},r),(r=ir.get(m))&&Id(n,r),g=l.createElement("script"),Mt(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){Zr.M(n,r);var l=Wa;if(l&&n){var u=Gt(l).hoistableScripts,m=Ya(n),g=u.get(m);g||(g=l.querySelector(eo(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=ir.get(m))&&Id(n,r),g=l.createElement("script"),Mt(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=le.current)?Hc(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=Gt(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=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(Jl(n)))&&!g._p&&(y.instance=g,y.state.loading=5),ir.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},ir.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Gt(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="'+ni(n)+'"'}function Jl(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),Ki(r,"link",l),Mt(r),n.head.appendChild(r))}function Ya(n){return'[src="'+ni(n)+'"]'}function eo(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+ni(l.href)+'"]');if(u)return r.instance=u,Mt(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"),Mt(u),Ki(u,"style",m),Uc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ga(l.href);var g=n.querySelector(Jl(m));if(g)return r.state.loading|=4,r.instance=g,Mt(g),g;u=P_(l),(m=ir.get(m))&&Pd(u,m),g=(n.ownerDocument||n).createElement("link"),Mt(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ki(g,"link",u),r.state.loading|=4,Uc(g,l.precedence,n),r.instance=g;case"script":return g=Ya(l.src),(m=n.querySelector(eo(g)))?(r.instance=m,Mt(m),m):(u=l,(m=ir.get(g))&&(u=x({},l),Id(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Mt(m),Ki(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,Uc(u,l.precedence,n));return r.instance}function Uc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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(Jl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Fc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Mt(g);return}g=r.ownerDocument||r,u=P_(u),(m=ir.get(m))&&Pd(u,m),g=g.createElement("link"),Mt(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ki(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=Fc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Hd=0;function rC(n,r){return n.stylesheets&&n.count===0&&Wc(n,n.stylesheets),0Hd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Fc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var qc=null;function Wc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,qc=new Map,r.forEach(sC,n),qc=null,Fc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=qc.get(n);if(l)var u=l.get(null);else{l=new Map,qc.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(),Kd.exports=SC(),Kd.exports}var CC=wC();const kC=Lu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 Jd="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,j)=>fetch(E,{...j,headers:{...j==null?void 0:j.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Jd}/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(`${Jd}/api/wallet/create`,{method:"POST"}),j=await E.json();if(!E.ok)throw new Error(j.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const j=await x(`${Jd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await j.json();if(!j.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(j){_(j instanceof Error?j.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 wu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const $p="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[j,I]=w.useState(""),[te,q]=w.useState(!1),[R,ie]=w.useState(null),[fe,be]=w.useState(""),[B,ne]=w.useState(null),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(null),[$,ge]=w.useState(null),T=w.useCallback((re,le)=>fetch(re,{...le,headers:{...le==null?void 0:le.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(re=>re.json()).then(re=>v(re)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(re=>re.ok?re.json():null).then(re=>{re&&ge(re)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!M.trim()){ie("Description is required");return}q(!0),ie(null);try{const re=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...j.trim()&&{genre:j}})}),le=await re.json();if(!re.ok)throw new Error(le.error||"Registration failed");v({linked:!0,agentId:le.agentId,owsWallet:le.owsWallet,txHash:le.txHash})}catch(re){ie(re instanceof Error?re.message:"Registration failed")}q(!1)},K=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}G(!0),U(null),ne(null);try{const re=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),le=await re.json();if(!re.ok)throw new Error(le.error||"Failed to generate binding code");ne(le)}catch(re){U(re instanceof Error?re.message:"Failed to generate binding code")}G(!1)},C=async(re,le)=>{await navigator.clipboard.writeText(re),z(le),setTimeout(()=>z(null),2e3)},X=async()=>{if(h(null),f(!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 re=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!re.ok){const le=await re.json();throw new Error(le.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(re){h(re instanceof Error?re.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:re=>N(re.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:re=>E(re.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:j,onChange:re=>I(re.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:te||!S.trim()||!M.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:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),wu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:$p}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:re=>be(re.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"}),Y&&d.jsx("p",{className:"text-error text-xs",children:Y}),d.jsx("button",{onClick:K,disabled:F||!fe.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:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:A==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:A==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:A==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:re=>s(re.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"}),d.jsx("input",{type:"password",value:a,onChange:re=>o(re.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:X,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ie=new Set(R);return ie.has(q)?ie.delete(q):ie.add(q),ie})},j=q=>{var ie;const R=q.map(fe=>{var be;return{file:fe.file,num:(be=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(fe=>fe.num!=null).sort((fe,be)=>parseInt(be.num)-parseInt(fe.num));return R.length>0?R[0].file:q.some(fe=>fe.file==="genesis.md")?"genesis.md":q.some(fe=>fe.file==="structure.md")?"structure.md":((ie=q[0])==null?void 0:ie.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=j(q.files);R&&s(q.name,R)}},te=q=>{const R=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...q].sort((ie,fe)=>R(ie.file)-R(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:te(q.files).map(R=>{const ie=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},ui=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Hf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",Uf={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Bs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ou(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",Os=" ",Po=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Cu}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 zy;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}},Cu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},lr=class Iy extends Po{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Cu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Bs(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()]}},mb="di$target",$f="di$dependencies",ef=new Map;function $C(e){return e[$f]||[]}function Fi(e){if(ef.has(e))return ef.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");FC(t,i,a)};return t._id=e,ef.set(e,t),t}function FC(e,t,i){t[mb]===t?t[$f].push({id:e,index:i}):(t[$f]=[{id:e,index:i}],t[mb]=t)}var pn=Fi("BufferService"),Hy=Fi("CoreMouseService"),ma=Fi("CoreService"),qC=Fi("CharsetService"),Fp=Fi("InstantiationService"),Uy=Fi("LogService"),mn=Fi("OptionsService"),$y=Fi("OscLinkService"),WC=Fi("UnicodeService"),Io=Fi("DecorationService"),Ff=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 lr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Ff=ui([Re(0,pn),Re(1,mn),Re(2,$y)],Ff);function GC(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 zu=Fi("CharSizeService"),ns=Fi("CoreBrowserService"),qp=Fi("MouseService"),rs=Fi("RenderService"),YC=Fi("SelectionService"),Fy=Fi("CharacterJoinerService"),ul=Fi("ThemeService"),qy=Fi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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)}},KC=new VC;function fu(e){XC(e)||KC.onUnexpectedError(e)}var qf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===qf&&e.message===qf}var ZC=class extends Error{constructor(){super(qf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Wf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Wf)return t;let i=new Wf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Gf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function In(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let q=te.length-1;q>=0;q--)yield te[q]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,q){let R=0;for(let ie of te)if(q(ie,R++))return!0;return!1}e.some=_;function x(te,q){for(let R of te)if(q(R))return R}e.find=x;function*b(te,q){for(let R of te)q(R)&&(yield R)}e.filter=b;function*v(te,q){let R=0;for(let ie of te)yield q(ie,R++)}e.map=v;function*S(te,q){let R=0;for(let ie of te)yield*q(ie,R++)}e.flatMap=S;function*N(...te){for(let q of te)yield*q}e.concat=N;function M(te,q,R){let ie=R;for(let fe of te)ie=q(ie,fe);return ie}e.reduce=M;function*E(te,q,R=te.length){for(q<0&&(q+=te.length),R<0?R+=te.length:R>te.length&&(R=te.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 tk(...e){return ii(()=>da(e))}function ii(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{da(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var zs=Yy,ht=class{constructor(){this._store=new zs,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)}};ht.None=Object.freeze({dispose(){}});var ll=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}},is=typeof window=="object"?window:globalThis,Yf=class Vf{constructor(t){this.element=t,this.next=Vf.Undefined,this.prev=Vf.Undefined}};Yf.Undefined=new Yf(void 0);var ri=Yf,xb=class{constructor(){this._first=ri.Undefined,this._last=ri.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ri.Undefined}clear(){let e=this._first;for(;e!==ri.Undefined;){let t=e.next;e.prev=ri.Undefined,e.next=ri.Undefined,e=t}this._first=ri.Undefined,this._last=ri.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ri(e);if(this._first===ri.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!==ri.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ri.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ri.Undefined&&e.next!==ri.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ri.Undefined&&e.next===ri.Undefined?(this._first=ri.Undefined,this._last=ri.Undefined):e.next===ri.Undefined?(this._last=this._last.prev,this._last.next=ri.Undefined):e.prev===ri.Undefined&&(this._first=this._first.next,this._first.prev=ri.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ri.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},Qi;(e=>{e.None=()=>ht.None;function t(F,G){return x(F,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(F){return(G,Y=null,U)=>{let A=!1,z;return z=F($=>{if(!A)return z?z.dispose():A=!0,G.call(Y,$)},null,U),A&&z.dispose(),z}}e.once=i;function s(F,G,Y){return f((U,A=null,z)=>F($=>U.call(A,G($)),null,z),Y)}e.map=s;function a(F,G,Y){return f((U,A=null,z)=>F($=>{G($),U.call(A,$)},null,z),Y)}e.forEach=a;function o(F,G,Y){return f((U,A=null,z)=>F($=>G($)&&U.call(A,$),null,z),Y)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(G,Y=null,U)=>{let A=tk(...F.map(z=>z($=>G.call(Y,$))));return _(A,U)}}e.any=h;function p(F,G,Y,U){let A=Y;return s(F,z=>(A=G(A,z),A),U)}e.reduce=p;function f(F,G){let Y,U={onWillAddFirstListener(){Y=F(A.fire,A)},onDidRemoveLastListener(){Y==null||Y.dispose()}},A=new we(U);return G==null||G.add(A),A.event}function _(F,G){return G instanceof Array?G.push(F):G&&G.add(F),F}function x(F,G,Y=100,U=!1,A=!1,z,$){let ge,T,D,K=0,C,X={leakWarningThreshold:z,onWillAddFirstListener(){ge=F(le=>{K++,T=G(T,le),U&&!D&&(re.fire(T),T=void 0),C=()=>{let V=T;T=void 0,D=void 0,(!U||K>1)&&re.fire(V),K=0},typeof Y=="number"?(clearTimeout(D),D=setTimeout(C,Y)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){A&&K>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,ge.dispose()}},re=new we(X);return $==null||$.add(re),re.event}e.debounce=x;function b(F,G=0,Y){return e.debounce(F,(U,A)=>U?(U.push(A),U):[A],G,void 0,!0,void 0,Y)}e.accumulate=b;function v(F,G=(U,A)=>U===A,Y){let U=!0,A;return o(F,z=>{let $=U||!G(z,A);return U=!1,A=z,$},Y)}e.latch=v;function S(F,G,Y){return[e.filter(F,G,Y),e.filter(F,U=>!G(U),Y)]}e.split=S;function N(F,G=!1,Y=[],U){let A=Y.slice(),z=F(T=>{A?A.push(T):ge.fire(T)});U&&U.add(z);let $=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new we({onWillAddFirstListener(){z||(z=F(T=>ge.fire(T)),U&&U.add(z))},onDidAddFirstListener(){A&&(G?setTimeout($):$())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(ge),ge.event}e.buffer=N;function M(F,G){return(Y,U,A)=>{let z=G(new j);return F(function($){let ge=z.evaluate($);ge!==E&&Y.call(U,ge)},void 0,A)}}e.chain=M;let E=Symbol("HaltChainable");class j{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(Y=>(G(Y),Y)),this}filter(G){return this.steps.push(Y=>G(Y)?Y:E),this}reduce(G,Y){let U=Y;return this.steps.push(A=>(U=G(U,A),U)),this}latch(G=(Y,U)=>Y===U){let Y=!0,U;return this.steps.push(A=>{let z=Y||!G(A,U);return Y=!1,U=A,z?A:E}),this}evaluate(G){for(let Y of this.steps)if(G=Y(G),G===E)break;return G}}function I(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.on(G,U),z=()=>F.removeListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromNodeEventEmitter=I;function te(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.addEventListener(G,U),z=()=>F.removeEventListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromDOMEventEmitter=te;function q(F){return new Promise(G=>i(F)(G))}e.toPromise=q;function R(F){let G=new we;return F.then(Y=>{G.fire(Y)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ie(F,G){return F(Y=>G.fire(Y))}e.forward=ie;function fe(F,G,Y){return G(Y),F(U=>G(U))}e.runAndSubscribe=fe;class be{constructor(G,Y){this._observable=G,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new we(U),Y&&Y.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,Y){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 B(F,G){return new be(F,G).emitter.event}e.fromObservable=B;function ne(F){return(G,Y,U)=>{let A=0,z=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(F.reportChanges(),z&&(z=!1,G.call(Y)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver($),F.reportChanges();let ge={dispose(){F.removeObserver($)}};return U instanceof zs?U.add(ge):Array.isArray(U)&&U.push(ge),ge}}e.fromObservableLight=ne})(Qi||(Qi={}));var Kf=class Xf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Xf._idPool++}`,Xf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Kf.all=new Set,Kf._idPool=0;var rk=Kf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||fu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new tf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof tf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof zs?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Zf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new we,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new we,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}};Zf.INSTANCE=new Zf;var Wp=Zf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Wp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Wp.INSTANCE.getZoomFactor(e)}Wp.INSTANCE.onDidChangeFullscreen;var hl=typeof navigator=="object"?navigator.userAgent:"",Qf=hl.indexOf("Firefox")>=0,gk=hl.indexOf("AppleWebKit")>=0,Gp=hl.indexOf("Chrome")>=0,xk=!Gp&&hl.indexOf("Safari")>=0;hl.indexOf("Electron/")>=0;hl.indexOf("Android")>=0;var nf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");nf=e.matches,pk(is,e,({matches:i})=>{nf&&t.matches||(nf=i)})}var il="en",Jf=!1,ep=!1,pu=!1,Jy=!1,Jc,mu=il,_b=il,_k,fr,ha=globalThis,Zi,Ty;typeof ha.vscode<"u"&&typeof ha.vscode.process<"u"?Zi=ha.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(Zi=process);var Ay,bk=typeof((Ay=Zi==null?void 0:Zi.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(Zi==null?void 0:Zi.type)==="renderer",Ry;if(typeof Zi=="object"){Jf=Zi.platform==="win32",ep=Zi.platform==="darwin",pu=Zi.platform==="linux",pu&&Zi.env.SNAP&&Zi.env.SNAP_REVISION,Zi.env.CI||Zi.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Jc=il,mu=il;let e=Zi.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Jc=t.userLocale,_b=t.osLocale,mu=t.resolvedLanguage||il,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(fr=navigator.userAgent,Jf=fr.indexOf("Windows")>=0,ep=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,pu=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,mu=globalThis._VSCODE_NLS_LANGUAGE||il,Jc=navigator.language.toLowerCase(),_b=Jc):console.error("Unable to resolve platform.");var e0=Jf,Tr=ep,yk=pu,bb=Jy,Ar=fr,As=mu,Sk;(e=>{function t(){return As}e.value=t;function i(){return As.length===2?As==="en":As.length>=3?As[0]==="e"&&As[1]==="n"&&As[2]==="-":!1}e.isDefaultVariant=i;function s(){return As==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ha.postMessage=="function"&&!ha.importScripts;(()=>{if(wk){let e=[];ha.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}),ha.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Ar&&Ar.indexOf("Chrome")>=0);Ar&&Ar.indexOf("Firefox")>=0;!Ck&&Ar&&Ar.indexOf("Safari")>=0;Ar&&Ar.indexOf("Edg/")>=0;Ar&&Ar.indexOf("Android")>=0;var Ka=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ka&&Ka.clipboard&&Ka.clipboard.writeText,bb||Ka&&Ka.clipboard&&Ka.clipboard.readText;var Yp=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}},rf=new Yp,vb=new Yp,yb=new Yp,kk=new Array(230),t0;(e=>{function t(h){return rf.keyCodeToStr(h)}e.toString=t;function i(h){return rf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 rf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Qi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new we),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Vp=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 Gf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Gf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Gf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=class rr{static fromArray(t){return new rr(i=>{i.emitMany(t)})}static fromPromise(t){return new rr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new rr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new rr(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 we,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 rr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return rr.map(this,t)}static filter(t,i){return new rr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return rr.filter(this,t)}static coalesce(t){return rr.filter(t,i=>!!i)}coalesce(){return rr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return rr.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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Nr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:is,disposables:new zs};e.set(is.vscodeWindowId,t);let i=new we,s=new we,a=new we;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 ht.None;let h=new zs,p={window:c,disposables:h.add(new zs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ze(c,Li.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Nr(c).document}}})(),Uk=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 Ze(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ze(e,t,i,s)},Kp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Nr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){fu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Nr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Li={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"},qk=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 Eo(e){return new qk(e)}var r0=class{constructor(){this._hooks=new zs,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(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Nr(e)}this._hooks.add(Ze(o,Li.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ze(o,Li.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 kr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(kr||(kr={}));var bo=class en extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Qi.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ze(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ze(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ze(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!en.isTouchDevice())return ht.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!en.isTouchDevice())return ht.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||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(kr.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],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(kr.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===kr.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===kr.Change||t.type===kr.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,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=en.SCROLL_FRICTION*x,h+=en.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(kr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};bo.SCROLL_FRICTION=-.005,bo.HOLD_DELAY=700,bo.CLEAR_TAP_COUNT_TIME=400,ui([Wk],bo,"isTouchDevice",1);var Gk=bo,Xp=class extends ht{onclick(e,t){this._register(Ze(e,Li.CLICK,i=>t(new eu(Nr(e),i))))}onmousedown(e,t){this._register(Ze(e,Li.MOUSE_DOWN,i=>t(new eu(Nr(e),i))))}onmouseover(e,t){this._register(Ze(e,Li.MOUSE_OVER,i=>t(new eu(Nr(e),i))))}onmouseleave(e,t){this._register(Ze(e,Li.MOUSE_LEAVE,i=>t(new eu(Nr(e),i))))}onkeydown(e,t){this._register(Ze(e,Li.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ze(e,Li.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ze(e,Li.INPUT,t))}onblur(e,t){this._register(Ze(e,Li.BLUR,t))}onfocus(e,t){this._register(Ze(e,Li.FOCUS,t))}onchange(e,t){this._register(Ze(e,Li.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Xp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Li.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Li.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Vp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Nr(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()}},Vk=class tp{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 tp(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 tp(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}}},Kk=class extends ht{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function sf(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Xp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=Eo(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(Ze(this.domNode.domNode,Li.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Eo(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(Ze(this.slider.domNode,Li.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=Fk(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(e0&&c>e2){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()}},a0=class np{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 np(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=np._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};rp.INSTANCE=new rp;var s2=rp,a2=class extends Xp{constructor(e,t,i){super(),this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new we),this.onWillScroll=this._onWillScroll.event,this._options=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=Eo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Eo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Eo(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 Vp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=da(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,Tr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=da(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ze(this._listenOnDomNode,Li.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Tr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Tr&&(t.className+=" mac"),t}var sp=class extends ht{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Qi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(Qi.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(f=>this._handleScroll(f)))}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}};sp=ui([Re(2,pn),Re(3,ns),Re(4,Hy),Re(5,ul),Re(6,mn),Re(7,rs)],sp);var ap=class extends ht{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(ii(()=>{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()}};ap=ui([Re(1,pn),Re(2,ns),Re(3,Io),Re(4,rs)],ap);var c2=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)}},wr={full:0,left:0,center:0,right:0},Rs={full:0,left:0,center:0,right:0},lo={full:0,left:0,center:0,right:0},ku=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{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);Rs.full=this._canvas.width,Rs.left=e,Rs.center=t,Rs.right=e,this._refreshDrawHeightConstants(),lo.full=1,lo.left=1,lo.center=1+Rs.left,lo.right=1+Rs.left+Rs.center}_refreshDrawHeightConstants(){wr.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);wr.left=t,wr.center=t,wr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.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(lo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-wr[e.position||"full"]/2),Rs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+wr[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}))}};ku=ui([Re(2,pn),Re(3,Io),Re(4,rs),Re(5,mn),Re(6,ul),Re(7,ns)],ku);var me;(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=""))(me||(me={}));var gu;(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="Ÿ"))(gu||(gu={}));var l0;(e=>e.ST=`${me.ESC}\\`)(l0||(l0={}));var lp=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)}}};lp=ui([Re(2,pn),Re(3,mn),Re(4,ma),Re(5,rs)],lp);var Oi=0,zi=0,Pi=0,oi=0,Db={css:"#00000000",rgba:0},Ci;(e=>{function t(a,o,c,h){return h!==void 0?`#${ra(a)}${ra(o)}${ra(c)}${ra(h)}`:`#${ra(a)}${ra(o)}${ra(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 Qt;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Oi=v+Math.round((_-v)*oi),zi=S+Math.round((x-S)*oi),Pi=N+Math.round((b-N)*oi);let M=Ci.toCss(Oi,zi,Pi),E=Ci.toRgba(Oi,zi,Pi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=xu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ci.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Oi,zi,Pi]=xu.toChannels(f),{css:Ci.toCss(Oi,zi,Pi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Oi,zi,Pi]=xu.toChannels(p.rgba),{css:Ci.toCss(Oi,zi,Pi,oi),rgba:Ci.toRgba(Oi,zi,Pi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var si;(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),Ci.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),oi=parseInt(a.slice(4,5).repeat(2),16),Ci.toColor(Oi,zi,Pi,oi);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]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ci.toColor(Oi,zi,Pi,oi);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,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ci.toRgba(Oi,zi,Pi,oi),css:a}}e.toColor=s})(si||(si={}));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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(un||(un={}));var xu;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Oi=x+Math.round((p-x)*oi),zi=b+Math.round((f-b)*oi),Pi=v+Math.round((_-v)*oi),Ci.toRgba(Oi,zi,Pi)}e.blend=t;function i(c,h,p){let f=un.relativeLuminance(c>>8),_=un.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=Qr(f,un.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Qr(un.relativeLuminance2(b,v,S),un.relativeLuminance2(f,_,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 ra(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Os.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,$=this._workCell;if(b.length>0&&G===b[0][0]&&A){let Ce=b.shift(),Ue=this._isCellInSelection(Ce[0],t);for(j=Ce[0]+1;j=Ce[1]),A?(U=!0,$=new u2(this._workCell,e.translateToString(!0,Ce[0],Ce[1]),Ce[1]-Ce[0]),z=Ce[1]-1,Y=$.getWidth()):B=Ce[1]}let ge=this._isCellInSelection(G,t),T=i&&G===o,D=F&&G>=f&&G<=_,K=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,Ce=>{K=!0});let C=$.getChars()||Os;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),be=Y*h-p.get(C,$.isBold(),$.isItalic()),!N)N=this._document.createElement("span");else if(M&&(ge&&fe||!ge&&!fe&&$.bg===I)&&(ge&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===q&&D===R&&be===ie&&!T&&!U&&!K&&A){$.isInvisible()?E+=Os:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=$.bg,te=$.fg,q=$.extended.ext,R=D,ie=be,fe=ge,U&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ne.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ne.push("xterm-cursor-blink"),ne.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ne.push("xterm-cursor-outline");break;case"block":ne.push("xterm-cursor-block");break;case"bar":ne.push("xterm-cursor-bar");break;case"underline":ne.push("xterm-cursor-underline");break}}if($.isBold()&&ne.push("xterm-bold"),$.isItalic()&&ne.push("xterm-italic"),$.isDim()&&ne.push("xterm-dim"),$.isInvisible()?E=Os:E=$.getChars()||Os,$.isUnderline()&&(ne.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Po.toColorRGB($.getUnderlineColor()).join(",")})`;else{let Ce=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&Ce<8&&(Ce+=8),N.style.textDecorationColor=v.ansi[Ce].css}$.isOverline()&&(ne.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ne.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let X=$.getFgColor(),re=$.getFgColorMode(),le=$.getBgColor(),V=$.getBgColorMode(),he=!!$.isInverse();if(he){let Ce=X;X=le,le=Ce;let Ue=re;re=V,V=Ue}let _e,Me,Le=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,Ce=>{Ce.options.layer!=="top"&&Le||(Ce.backgroundColorRGB&&(V=50331648,le=Ce.backgroundColorRGB.rgba>>8&16777215,_e=Ce.backgroundColorRGB),Ce.foregroundColorRGB&&(re=50331648,X=Ce.foregroundColorRGB.rgba>>8&16777215,Me=Ce.foregroundColorRGB),Le=Ce.options.layer==="top")}),!Le&&ge&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,le=_e.rgba>>8&16777215,V=50331648,Le=!0,v.selectionForeground&&(re=50331648,X=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Le&&ne.push("xterm-decoration-top");let He;switch(V){case 16777216:case 33554432:He=v.ansi[le],ne.push(`xterm-bg-${le}`);break;case 50331648:He=Ci.toColor(le>>16,le>>8&255,le&255),this._addStyle(N,`background-color:#${Mb((le>>>0).toString(16),"0",6)}`);break;case 0:default:he?(He=v.foreground,ne.push("xterm-bg-257")):He=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(He,.5)),re){case 16777216:case 33554432:$.isBold()&&X<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(X+=8),this._applyMinimumContrast(N,He,v.ansi[X],$,_e,void 0)||ne.push(`xterm-fg-${X}`);break;case 50331648:let Ce=Ci.toColor(X>>16&255,X>>8&255,X&255);this._applyMinimumContrast(N,He,Ce,$,_e,Me)||this._addStyle(N,`color:#${Mb(X.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,He,v.foreground,$,_e,Me)||he&&ne.push("xterm-fg-257")}ne.length&&(N.className=ne.join(" "),ne.length=0),!T&&!U&&!K&&A?M++:N.textContent=E,be!==this.defaultSpacing&&(N.style.letterSpacing=`${be}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=Qt.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]}};op=ui([Re(1,Fy),Re(2,mn),Re(3,ns),Re(4,ma),Re(5,Io),Re(6,ul)],op);function Mb(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}},g2=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 x2(){return new g2}var af="xterm-dom-renderer-owner-",nr="xterm-rows",iu="xterm-fg-",Bb="xterm-bg-",oo="xterm-focus",nu="xterm-selection",_2=1,cp=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new we).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(nr),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(nu),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(op,document),this._element.classList.add(af+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(af+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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} .${nr} 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} .${nr} { 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} .${nr} .xterm-dim { color: ${Qt.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} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${nr}.${oo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${nr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${nu} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${nu} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${nu} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${iu}${o} { color: ${c.css}; }${this._terminalSelector} .${iu}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${iu}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${iu}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(oo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(oo),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${af}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};cp=ui([Re(7,Fp),Re(8,zu),Re(9,mn),Re(10,pn),Re(11,ma),Re(12,ns),Re(13,ul)],cp);var up=class extends ht{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new we),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};up=ui([Re(2,mn)],up);var o0=class extends ht{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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=class extends ht{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 S2(this._window)),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new we),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Qi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ze(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ze(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}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ll),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ze(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)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ii(()=>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 Zp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Zp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var hp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Zp(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])}}};hp=ui([Re(0,rs),Re(1,zu)],hp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Qp,isMac:()=>Nu,isNode:()=>Pu,isSafari:()=>h0,isWindows:()=>d0});var Pu=typeof process<"u"&&"title"in process,Ho=Pu?"node":navigator.userAgent,Uo=Pu?"node":navigator.platform,u0=Ho.includes("Firefox"),E2=Ho.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Ho);function N2(){if(!h0)return 0;let e=Ho.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Nu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Uo),j2=Uo==="iPad",T2=Uo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(Uo),Qp=Uo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Ho),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},ju=!Pu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new ju}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},dp=class extends ht{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 ll),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new ll),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 we),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new we),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new we),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ii(()=>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()}};dp=ui([Re(2,mn),Re(3,zu),Re(4,ma),Re(5,Io),Re(6,pn),Re(7,ns),Re(8,ul)],dp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+Iu(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Do(Math.abs(a-e),Ro(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Do(p,Ro(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return Iu(t,s,a,o).length===0?"":Do(g0(e,t,e,t-fa(t,a),!1,a).length,Ro("D",o))}function Iu(e,t,i,s){let a=e-fa(e,i),o=t-fa(t,i),c=Math.abs(a-o)-I2(e,t,i);return Do(c,Ro(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;Iu(t,s,a,o).length>0?c=s-fa(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Do(g0(e,c,i,h,p==="C",a).length,Ro(p,o))}function I2(e,t,i){var c;let s=0,a=e-fa(e,i),o=t-fa(t,i);for(let h=0;h=0&&e0?c=s-fa(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Ro(e,t){let i=t?"O":"[";return me.ESC+i+e}function Do(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 Lb(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 lf=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),fp=class extends ht{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 lr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new we),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new we),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Qp&&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=Lb(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=Zp(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,-lf),lf),t/=lf,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Nu?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(),F2)}_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&&!(Nu&&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,f=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+=j-1,p+=j-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let j=this._bufferService.cols-E.start;S-=j,N+=j}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};fp=ui([Re(3,pn),Re(4,ma),Re(5,qp),Re(6,mn),Re(7,rs),Re(8,ns)],fp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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=[si.toColor("#2e3436"),si.toColor("#cc0000"),si.toColor("#4e9a06"),si.toColor("#c4a000"),si.toColor("#3465a4"),si.toColor("#75507b"),si.toColor("#06989a"),si.toColor("#d3d7cf"),si.toColor("#555753"),si.toColor("#ef2929"),si.toColor("#8ae234"),si.toColor("#fce94f"),si.toColor("#729fcf"),si.toColor("#ad7fa8"),si.toColor("#34e2e2"),si.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})()),oa=si.toColor("#ffffff"),vo=si.toColor("#000000"),Pb=si.toColor("#ffffff"),Ib=vo,co={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=oa,pp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new we),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:oa,background:vo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:co,selectionBackgroundOpaque:Qt.blend(vo,co),selectionInactiveBackgroundTransparent:co,selectionInactiveBackgroundOpaque:Qt.blend(vo,co),scrollbarSliderBackground:Qt.opacity(oa,.2),scrollbarSliderHoverBackground:Qt.opacity(oa,.4),scrollbarSliderActiveBackground:Qt.opacity(oa,.5),overviewRulerBorder:oa,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=$t(e.foreground,oa),t.background=$t(e.background,vo),t.cursor=Qt.blend(t.background,$t(e.cursor,Pb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=$t(e.selectionBackground,co),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,Y2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",mp=class extends ht{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=X2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Bs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return ru=t*ut,i.content=this._data[ru+0],i.fg=this._data[ru+1],i.bg=this._data[ru+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Bs(i):a&2097151?(this._combined[t]=Bs(a&2097151)+Bs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*of=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cMo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Mo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new we),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),da(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Di={},ca=Di.B;Di[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=ca,this.markers=[],this._nullCell=lr.fromCharData([0,Oy,1,0]),this._whitespaceCell=lr.fromCharData([0,Os,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new ju,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Cu),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 Cu),this._whitespaceCell}getBlankLine(e,t){return new yo(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&&eUb?Ub: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 Hb(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 yo(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(wi),i);if(s.length>0){let a=J2(this.lines,s);eE(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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let te=Math.max(M,0);E=Mo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends ht{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new we),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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,gp=class extends ht{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};gp=ui([Re(0,mn)],gp);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:Nu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new we),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(ii(()=>{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]),!aE(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=rE.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 aE(e){return e==="block"||e==="underline"||e==="bar"}function So(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]&&So(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),xp=class extends ht{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 we),this.onData=this._onData.event,this._onUserInput=this._register(new we),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new we),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=So(Fb),this.decPrivateModes=So(qb)}reset(){this.modes=So(Fb),this.decPrivateModes=So(qb)}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))}};xp=ui([Re(0,pn),Re(1,Uy),Re(2,mn)],xp);var Wb={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 cf(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 uf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[cf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${uf(t[0])}${uf(t[1])}${uf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.x};${e.y}${t}`}},_p=class extends ht{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 we),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};_p=ui([Re(0,pn),Re(1,ma),Re(2,mn)],_p);var hf=[[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]],lE=[[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]],Ai;function oE(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=ua.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ua.createPropertyValue(0,i,s)}},ua=class _u{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new we,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=_u.extractWidth(h);_u.extractShouldJoin(h)&&(p-=_u.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 uo=2147483647,hE=256,S0=class bp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 bp;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>uo?uo: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>uo?uo: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,uo):t}},ho=[],dE=class{constructor(){this._state=0,this._active=ho,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=ho}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=ho,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ho,!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",Ou(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=ho,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+=Ou(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}},fo=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=fo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fo}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=fo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||fo,!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",Ou(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=fo,this._ident=0}},wo=new S0;wo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=wo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():wo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Ou(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=wo,this._data="",this._hitLimit=!1,i));return this._params=wo,this._data="",this._hitLimit=!1,t}},pE=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(sr,0,2,0),e.add(sr,8,5,8),e.add(sr,6,0,6),e.add(sr,11,0,11),e.add(sr,13,13,13),e})(),gE=class extends ht{constructor(e=mE){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 S0,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(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 df(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${df(i,t)}/${df(s,t)}/${df(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ds=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone(),this._onRequestBell=this._register(new we),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new we),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new we),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new we),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new we),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new we),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new we),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new we),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new we),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 vp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(gu.IND,()=>this.index()),this._parser.setExecuteHandler(gu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(gu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Hn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Hn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Hn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Hn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Hn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Hn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Hn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Hn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Hn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Hn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Hn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Hn(f=>this.restoreCursorColor(f))),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 f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>Ds&&(o=this._parseStack.position+Ds)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthDs)for(let f=o;f0&&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,j=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof yo&&x.copyCellsFrom(E,j,0,M,!1);j=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(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 f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Po.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(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.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(`${me.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(!Zb(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(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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 lr;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(`${me.ESC}${c}${me.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)}},vp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vp=ui([Re(0,pn)],vp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{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 we),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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},yp=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)))}};yp=ui([Re(0,pn)],yp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ll),this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onData=this._register(new we),this.onData=this._onData.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new we),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new we),this._instantiationService=new K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(mn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(pn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(ma,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ua)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(yp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Qi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Qi.forward(this._bufferService.onResize,this._onResize)),this._register(Qi.forward(this.coreService.onData,this._onData)),this._register(Qi.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(Qi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new we),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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.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=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=EE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.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=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var gi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new ju,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new ju,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||(gi=this._search(t),gi===-1)||this._getKey(this._array[gi])!==t)return!1;do if(this._array[gi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(gi),!0;while(++gia-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&&(gi=this._search(e),!(gi<0||gi>=this._array.length)&&this._getKey(this._array[gi])===e))do yield this._array[gi];while(++gi=this._array.length)&&this._getKey(this._array[gi])===e))do t(this._array[gi]);while(++gi=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}},ff=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new we),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new we),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{ff=a.options.x??0,nv=ff+(a.options.width??1),e>=ff&&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)}},rv=20,Tu=class extends ht{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 DE(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(Ze(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{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===rv+1&&(this._liveRegion.textContent+=Uf.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;da(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(Ze(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ze(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ze(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ze(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,da(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}}};Sp=ui([Re(1,qp),Re(2,rs),Re(3,pn),Re(4,qy)],Sp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new ll),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ll),this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new we),this.onKey=this._onKey.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new we),this.onBell=this._onBell.event,this._onFocus=this._register(new we),this._onBlur=this._register(new we),this._onA11yCharEmitter=this._register(new we),this._onA11yTabEmitter=this._register(new we),this._onWillOpen=this._register(new we),this._setup(),this._decorationService=this._instantiationService.createInstance(TE),this._instantiationService.setService(Io,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ff)),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(Qi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Qi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Qi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Qi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{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=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${bE(a)}${l0.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(me.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(me.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(Ze(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ze(this.textarea,"paste",e)),this._register(Ze(this.element,"paste",e)),u0?this._register(Ze(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ze(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Qp&&this._register(Ze(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ze(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ze(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ze(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ze(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ze(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ze(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ze(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(Ze(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",Hf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Ze(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ze(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(up,this._document,this._helperContainer),this._instantiationService.setService(zu,this._charSizeService),this._themeService=this._instantiationService.createInstance(pp),this._instantiationService.setService(ul,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Eu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(dp,this.rows,this.screenElement)),this._instantiationService.setService(rs,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(lp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hp),this._instantiationService.setService(qp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(Sp,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(sp,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(fp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(Qi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(ap,this.screenElement)),this._register(Ze(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(ku,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ku,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(cp,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ze(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(Ze(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.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){By(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=NE(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===me.ETX||i.key===me.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)&&(LE(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 lr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=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 zE(t)}getNullCell(){return new lr}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new we),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Cr=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 Hf.get()},set promptLabel(e){Hf.set(e)},get tooMuchOutput(){return Uf.get()},set tooMuchOutput(e){Uf.set(e)}}}_verifyIntegers(...e){for(Cr of e)if(Cr===1/0||isNaN(Cr)||Cr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Cr of e)if(Cr&&(Cr===1/0||isNaN(Cr)||Cr%1!==0||Cr<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var FE=2,qE=1,WE=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,f=s-h,_=a-p-t;return{cols:Math.max(FE,Math.floor(_/e.css.cell.width)),rows:Math.max(qE,Math.floor(f/e.css.cell.height))}}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var Ii=0,Hi=0,Ui=0,ci=0,tn;(e=>{function t(a,o,c,h){return h!==void 0?`#${sa(a)}${sa(o)}${sa(c)}${sa(h)}`:`#${sa(a)}${sa(o)}${sa(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 GE;(e=>{function t(p,f){if(ci=(f.rgba&255)/255,ci===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Ii=v+Math.round((_-v)*ci),Hi=S+Math.round((x-S)*ci),Ui=N+Math.round((b-N)*ci);let M=tn.toCss(Ii,Hi,Ui),E=tn.toRgba(Ii,Hi,Ui);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=bu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return tn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Ii,Hi,Ui]=bu.toChannels(f),{css:tn.toCss(Ii,Hi,Ui),rgba:f}}e.opaque=a;function o(p,f){return ci=Math.round(f*255),[Ii,Hi,Ui]=bu.toChannels(p.rgba),{css:tn.toCss(Ii,Hi,Ui,ci),rgba:tn.toRgba(Ii,Hi,Ui,ci)}}e.opacity=o;function c(p,f){return ci=p.rgba&255,o(p,ci*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var Xi;(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 Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),tn.toColor(Ii,Hi,Ui);case 5:return Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),ci=parseInt(a.slice(4,5).repeat(2),16),tn.toColor(Ii,Hi,Ui,ci);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 Ii=parseInt(o[1]),Hi=parseInt(o[2]),Ui=parseInt(o[3]),ci=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),tn.toColor(Ii,Hi,Ui,ci);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),[Ii,Hi,Ui,ci]=t.getImageData(0,0,1,1).data,ci!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:tn.toRgba(Ii,Hi,Ui,ci),css:a}}e.toColor=s})(Xi||(Xi={}));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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var bu;(e=>{function t(c,h){if(ci=(h&255)/255,ci===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Ii=x+Math.round((p-x)*ci),Hi=b+Math.round((f-b)*ci),Ui=v+Math.round((_-v)*ci),tn.toRgba(Ii,Hi,Ui)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=Jr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=Jr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,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})(bu||(bu={}));function sa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Xi.toColor("#2e3436"),Xi.toColor("#cc0000"),Xi.toColor("#4e9a06"),Xi.toColor("#c4a000"),Xi.toColor("#3465a4"),Xi.toColor("#75507b"),Xi.toColor("#06989a"),Xi.toColor("#d3d7cf"),Xi.toColor("#555753"),Xi.toColor("#ef2929"),Xi.toColor("#8ae234"),Xi.toColor("#fce94f"),Xi.toColor("#729fcf"),Xi.toColor("#ad7fa8"),Xi.toColor("#34e2e2"),Xi.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 av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(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=!C0(e,t),a=!es(e,t),o=!k0(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?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(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&&(es(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!es(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",Za="[REDACTED]",JE=[[/(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 lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,Ps="scrollback",cv=10*1024*1024;function Jp(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ps)||s.createObjectStore(Ps)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Qa(e,t){const i=t.length>cv?t.slice(-cv):t,s=await Jp();return new Promise((a,o)=>{const c=s.transaction(Ps,"readwrite");c.objectStore(Ps).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await Jp();return new Promise((i,s)=>{const o=t.transaction(Ps,"readonly").objectStore(Ps).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function pf(e){const t=await Jp();return new Promise((i,s)=>{const a=t.transaction(Ps,"readwrite");a.objectStore(Ps).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[j,I]=w.useState(new Set),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(!1),[B,ne]=w.useState(!1),F=eN(x,_),G=!!b,Y=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const U=w.useCallback(V=>{var _e;const{width:he}=V.container.getBoundingClientRect();if(!(he<50))try{V.fit.fit(),((_e=V.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&V.ws.send(JSON.stringify({type:"resize",cols:V.term.cols,rows:V.term.rows}))}catch{}},[]),A=w.useCallback(V=>{for(const[he,_e]of Ri)_e.container.style.display=he===V?"block":"none";if(V){const he=Ri.get(V);he&&setTimeout(()=>U(he),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const ge=w.useCallback((V,he,_e)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Le=z.current[V]?"&bypass=true":"",He=$.current[V],Ce=He?`&provider=${encodeURIComponent(He)}`:"",Ue=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(V)}&token=${e}&resume=${_e}${Le}${Ce}`);Ue.onopen=()=>{he.connected=!0,he._retried=!1,I(at=>{const Ke=new Set(at);return Ke.delete(V),Ke}),Ue.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let et=!0;Ue.onmessage=at=>{if(et&&(et=!1,typeof at.data=="string"&&at.data===QE)){he.term.reset(),pf(V).catch(()=>{});return}he.term.write(typeof at.data=="string"?lv(at.data):at.data)},Ue.onclose=at=>{if(he.connected=!1,he.ws===Ue){he.ws=null;try{const Ke=he.serialize.serialize();Qa(V,Ke).catch(()=>{})}catch{}if(at.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r -\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),Y.current(V,he,!1);return}I(Ke=>new Set(Ke).add(V))}},he.term.onData(at=>{Ue.readyState===WebSocket.OPEN&&Ue.send(at)}),he.ws=Ue},[e]);w.useEffect(()=>{Y.current=ge},[ge]);const T=w.useCallback(async(V,he)=>{if(!S.current||Ri.has(V))return;const{resume:_e=!1,autoConnect:Me=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const He=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),Ce=new WE,Ue=new XE;He.loadAddon(Ce),He.loadAddon(Ue),He.open(Le);const et={term:He,fit:Ce,serialize:Ue,ws:null,container:Le,observer:null,connected:!1},at=new ResizeObserver(()=>{var Et;const{width:Ke}=Le.getBoundingClientRect();if(!(Ke<50))try{Ce.fit(),((Et=et.ws)==null?void 0:Et.readyState)===WebSocket.OPEN&&et.ws.send(JSON.stringify({type:"resize",cols:He.cols,rows:He.rows}))}catch{}});at.observe(Le),et.observer=at,Ri.set(V,et),E(Ke=>[...Ke,V]);try{const Ke=await rN(V);if(Ke){const Et=lv(Ke);He.write(Et),Et!==Ke&&Qa(V,Et).catch(()=>{})}}catch{}Me?ge(V,et,_e):I(Ke=>new Set(Ke).add(V)),setTimeout(()=>U(et),50)},[ge,U]),D=w.useCallback(async(V,he)=>{const _e=Ri.get(V);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),ge(V,_e,he))},[ge]),K=w.useCallback(V=>{const he=Ri.get(V);if(he){try{const _e=he.serialize.serialize();Qa(V,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(V),E(_e=>_e.filter(Me=>Me!==V)),I(_e=>{const Me=new Set(_e);return Me.delete(V),Me}),i(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(V)}},[i,a]),C=w.useCallback(V=>{var _e;const he=Ri.get(V);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit -`),pf(V).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(V),E(Me=>Me.filter(Le=>Le!==V)),I(Me=>{const Le=new Set(Me);return Le.delete(V),Le}),i(`/api/terminal/${encodeURIComponent(V)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(V))},[i,a]),X=w.useCallback(async(V,he,_e)=>{const Me=Ri.get(V);if(!Me||Ri.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:V,newName:he,..._e??{}})})).ok)return!1;Ri.delete(V),Ri.set(he,Me);try{const He=Me.serialize.serialize();await pf(V),await Qa(he,He)}catch{}return E(He=>He.map(Ce=>Ce===V?he:Ce)),I(He=>{if(!He.has(V))return He;const Ce=new Set(He);return Ce.delete(V),Ce.add(he),Ce}),(Me.connected||Me.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),Y.current(he,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=X),()=>{h&&(h.current=null)}),[h,X]),w.useEffect(()=>{if(t){if(F){A(null);return}if(G){A(null);return}Ri.has(t)?A(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(V=>V.ok?V.json():null).then(V=>{if(!Ri.has(t)){const he=(V==null?void 0:V.sessionId)&&!(V!=null&&V.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,F,G]),w.useEffect(()=>{const V=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Me=_e.serialize.serialize();Qa(he,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(V)},[]),w.useEffect(()=>()=>{for(const[V,he]of Ri){try{const _e=he.serialize.serialize();Qa(V,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(V)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const re=t?j.has(t):!1,le=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!le&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(V=>d.jsxs("div",{onClick:()=>s==null?void 0:s(V),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${V===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${j.has(V)?"bg-amber-500":V===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${V.startsWith("_new_")?"italic":""}`,children:V.startsWith("_new_")?"Untitled":V}),d.jsx("button",{onClick:he=>{he.stopPropagation(),V.startsWith("_new_")?q(V):K(V)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},V)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>ie(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),le&&!F&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):wu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[$p," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),be(!0),setTimeout(()=>be(!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:fe?"Copied!":"Copy"})]})]})]})}),G&&!F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){ne(!0);try{await(v==null?void 0:v())}finally{ne(!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:B?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const V=te;q(null),C(V)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const V=R;ie(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:V})})).ok&&(K(V),o==null||o(V))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),re&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class $o{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}$o.prototype.normal={};$o.prototype.property={};$o.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new $o(i,s,t)}function wp(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 dN=0;const ot=ga(),Si=ga(),Cp=ga(),ve=ga(),Yt=ga(),rl=ga(),Un=ga();function ga(){return 2**++dN}const kp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Si,commaOrSpaceSeparated:Un,commaSeparated:rl,number:ve,overloadedBoolean:Cp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),mf=Object.keys(kp);class em extends Nn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=em}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),tm=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var Ja={},gf,pv;function wN(){if(pv)return gf;pv=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=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var j=1,I=1;function te(Y){var U=Y.match(t);U&&(j+=U.length);var A=Y.lastIndexOf(p);I=~A?Y.length-A:I+Y.length}function q(){var Y={line:j,column:I};return function(U){return U.position=new R(Y),be(),U}}function R(Y){this.start=Y,this.end={line:j,column:I},this.source=E.source}R.prototype.content=M;function ie(Y){var U=new Error(E.source+":"+j+":"+I+": "+Y);if(U.reason=Y,U.filename=E.source,U.line=j,U.column=I,U.source=M,!E.silent)throw U}function fe(Y){var U=Y.exec(M);if(U){var A=U[0];return te(A),M=M.slice(A.length),U}}function be(){fe(i)}function B(Y){var U;for(Y=Y||[];U=ne();)U!==!1&&Y.push(U);return Y}function ne(){var Y=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var U=2;x!=M.charAt(U)&&(_!=M.charAt(U)||f!=M.charAt(U+1));)++U;if(U+=2,x===M.charAt(U-1))return ie("End of comment missing");var A=M.slice(2,U-2);return I+=2,te(A),M=M.slice(U),I+=2,Y({type:b,comment:A})}}function F(){var Y=q(),U=fe(s);if(U){if(ne(),!fe(a))return ie("property missing ':'");var A=fe(o),z=Y({type:v,property:N(U[0].replace(e,x)),value:A?N(A[0].replace(e,x)):x});return fe(c),z}}function G(){var Y=[];B(Y);for(var U;U=F();)U!==!1&&(Y.push(U),B(Y));return Y}return be(),G()}function N(M){return M?M.replace(h,x):x}return gf=S,gf}var mv;function CN(){if(mv)return Ja;mv=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(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return Ja}var po={},gv;function kN(){if(gv)return po;gv=1,Object.defineProperty(po,"__esModule",{value:!0}),po.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return po.camelCase=p,po}var mo,xv;function EN(){if(xv)return mo;xv=1;var e=mo&&mo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,mo=s,mo}var NN=EN();const jN=Lu(NN),M0=B0("end"),im=B0("start");function B0(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 L0(e){const t=im(e),i=M0(e);if(t&&i)return{start:t,end:i}}function No(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Ep(e):""}function Ep(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Ep(e&&e.start)+"-"+Ep(e&&e.end)}function bv(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=No(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 nm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?tm:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=tm,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=sm(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),rm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}Bo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Bo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=tm,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=sm(e,t);return P0(e,c,o,t),rm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return rm(s,sm(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function rm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=im(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&nm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 Bo(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 Bo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function sm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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 Sv={}.hasOwnProperty;function U0(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 fn=Is(/[A-Za-z]/),nn=Is(/[\dA-Za-z]/),JN=Is(/[#-'*+\--9=?A-Z^-~]/);function Au(e){return e!==null&&(e<32||e===127)}const Np=Is(/\d/),e5=Is(/[\dA-Fa-f]/),t5=Is(/[!-/:-@[-`{-~]/);function Ye(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 Hu=Is(new RegExp("\\p{P}|\\p{S}","u")),pa=Is(/\s/);function Is(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function fl(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 kt(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 ie=t.events.length;let fe=ie,be,B;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(be){B=t.events[fe][1].end;break}be=!0}for(E(s),R=ie;RI;){const q=i[te];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function j(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ol(e){if(e===null||qt(e)||pa(e))return 1;if(Hu(e))return 2}function Uu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=ar(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=ar(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=ar(f,Uu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=ar(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=ar(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,$n(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&xt(R)?kt(e,j,"linePrefix",o+1)(R):j(R)}function j(R){return R===null||Ye(R)?e.check(kv,N,te)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),j(R)):(e.consume(R),I)}function te(R){return e.exit("codeFenced"),t(R)}function q(R,ie,fe){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),ne}function ne(U){return R.enter("codeFencedFence"),xt(U)?kt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),G(U)):fe(U)}function G(U){return U===h?(be++,R.consume(U),G):be>=c?(R.exit("codeFencedFenceSequence"),xt(U)?kt(R,Y,"whitespace")(U):Y(U)):fe(U)}function Y(U){return U===null||Ye(U)?(R.exit("codeFencedFence"),ie(U)):fe(U)}}}function _5(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 _f={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(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):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&go(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),go(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),go(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Au(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||qt(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):Ye(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||Ye(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 K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function jo(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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 qt(v)?jo(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return xt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return qt(h)?jo(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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 U5(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||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):xt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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):fn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):fn(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 S(C){const X="CDATA[";return C===X.charCodeAt(h++)?(e.consume(C),h===X.length?s.interrupt?t:F:S):i(C)}function N(C){return fn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||qt(C)){const X=C===47,re=c.toLowerCase();return!X&&!o&&Nv.includes(re)?(a=1,s.interrupt?t(C):F(C)):$5.includes(c.toLowerCase())?(a=6,X?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?j(C):I(C))}return C===45||nn(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function j(C){return xt(C)?(e.consume(C),j):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||fn(C)?(e.consume(C),te):xt(C)?(e.consume(C),I):B(C)}function te(C){return C===45||C===46||C===58||C===95||nn(C)?(e.consume(C),te):q(C)}function q(C){return C===61?(e.consume(C),R):xt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ie):xt(C)?(e.consume(C),R):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,be):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),fe)}function be(C){return C===47||C===62||xt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),ne):i(C)}function ne(C){return C===null||Ye(C)?F(C):xt(C)?(e.consume(C),ne):i(C)}function F(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),ge):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,K,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),F)}function G(C){return e.check(W5,Y,K)(C)}function Y(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),F(C))}function A(C){return C===45?(e.consume(C),T):F(C)}function z(C){return C===47?(e.consume(C),c="",$):F(C)}function $(C){if(C===62){const X=c.toLowerCase();return Nv.includes(X)?(e.consume(C),D):F(C)}return fn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):F(C)}function ge(C){return C===93?(e.consume(C),T):F(C)}function T(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),T):F(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),K(C)):(e.consume(C),D)}function K(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Fo,t,i)}}const X5={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),f):T===47?(e.consume(T),q):T===63?(e.consume(T),I):fn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):fn(T)?(e.consume(T),j):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):Ye(T)?(c=x,z(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const D="CDATA[";return T===D.charCodeAt(o++)?(e.consume(T),o===D.length?N:S):i(T)}function N(T){return T===null?i(T):T===93?(e.consume(T),M):Ye(T)?(c=N,z(T)):(e.consume(T),N)}function M(T){return T===93?(e.consume(T),E):N(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):N(T)}function j(T){return T===null||T===62?A(T):Ye(T)?(c=j,z(T)):(e.consume(T),j)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,z(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function q(T){return fn(T)?(e.consume(T),R):i(T)}function R(T){return T===45||nn(T)?(e.consume(T),R):ie(T)}function ie(T){return Ye(T)?(c=ie,z(T)):xt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||nn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?be(T):i(T)}function be(T){return T===47?(e.consume(T),A):T===58||T===95||fn(T)?(e.consume(T),B):Ye(T)?(c=be,z(T)):xt(T)?(e.consume(T),be):A(T)}function B(T){return T===45||T===46||T===58||T===95||nn(T)?(e.consume(T),B):ne(T)}function ne(T){return T===61?(e.consume(T),F):Ye(T)?(c=ne,z(T)):xt(T)?(e.consume(T),ne):be(T)}function F(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):Ye(T)?(c=F,z(T)):xt(T)?(e.consume(T),F):(e.consume(T),Y)}function G(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=G,z(T)):(e.consume(T),G)}function Y(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?be(T):(e.consume(T),Y)}function U(T){return T===47||T===62||qt(T)?be(T):i(T)}function A(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"),$}function $(T){return xt(T)?kt(e,ge,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):ge(T)}function ge(T){return e.enter("htmlTextData"),c(T)}}const om={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),xt(f)?kt(e,h,"whitespace")(f):h(f))}}const En={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Np(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(vu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Np(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Fo,s.interrupt?i:_,e.attempt(fj,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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Fo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(En,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return kt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return kt(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 jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),xt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Fo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++i0){const Wt=je.tokenStack[je.tokenStack.length-1];(Wt[1]||Av).call(je,void 0,Wt[0])}for(xe.position={start:Ms(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Ms(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=fl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:fl(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 aT(e,t){const i={src:fl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:fl(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 cT(e,t){const i={href:fl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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 dT(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=im(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:su,yaml:su,definition:su,footnoteDefinition:su};function su(){}const iS=-1,$u=0,To=1,Ru=2,cm=3,um=4,hm=5,dm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 $u:case iS:return i(c,a);case To:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Ru:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case cm:return i(new Date(c),a);case um:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case hm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case dm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),el="",{toString:CT}={},{keys:kT}=Object,xo=e=>{const t=typeof e;if(t!=="object"||!e)return[$u,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[To,el];case"Object":return[Ru,el];case"Date":return[cm,el];case"RegExp":return[um,el];case"Map":return[hm,el];case"Set":return[dm,el];case"DataView":return[To,i]}return i.includes("Array")?[To,i]:i.includes("Error")?[nS,i]:[Ru,i]},au=([e,t])=>e===$u&&(t==="function"||t==="symbol"),ET=(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]=xo(c);switch(h){case $u:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case To:{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 Ru:{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 kT(c))(e||!au(xo(c[b])))&&_.push([o(b),o(c[b])]);return x}case cm:return a([h,c.toISOString()],c);case um:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case hm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(au(xo(b))||au(xo(v))))&&_.push([o(b),o(v)]);return x}case dm:{const _=[],x=a([h,_],c);for(const b of c)(e||!au(xo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Lo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let j=typeof i=="string"?i:i(p,v);typeof j=="string"&&(j={type:"text",value:j}),S.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(j)?j:[j]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const j=M.children[M.children.length-1];j&&j.type==="text"?j.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Lo(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 Fu=(function(e){if(e==null)return MT;if(typeof e=="function")return qu(e);if(typeof e=="object")return Array.isArray(e)?AT(e):RT(e);if(typeof e=="string")return DT(e);throw new Error("Expected function, string, or object as test")});function AT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Tp))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` -`}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var vf,Hv;function WT(){if(Hv)return vf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return vf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,j=!1;for(typeof N=="boolean"&&(j=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 Er={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');qo(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 XT(e){if(qo(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 ZT(e){qo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 qo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Dp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Dp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Rp(N)&&Rp(v)&&(v=yf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new pm().freeze();function kf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Nf(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 $v(e){if(!Rp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function lu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return fm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 xf)if(Object.hasOwn(xf,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=xf[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Fu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=te+1:(S!==te&&j.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(R)?j.push(...R):R&&j.push(R),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||pa(i)||Hu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(j)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=j),v[x]=j),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(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 oR(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 cR(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 uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=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),f(),_}function hR(e,t,i){return(i?"":" ")+e}function mm(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 dR(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Oo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Du(e,t,i){const s=ol(e),a=ol(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Du(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Du(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return fm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Tp}),!!((!e.depth||e.depth<3)&&am(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` -`,after:` -`});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 f=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(f)&&(f=Oo(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=mm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function gm(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 wR(e){const t=gm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):gm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Fu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Du(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Du(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Rf,tableHeader:Rf,tableRow:Rf}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Rf(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),j=f([E]);return j.slice(0,j.indexOf(` -`))}function p(v,S,N,M){const E=N.enter("tableCell"),j=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return j(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const j=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=pr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(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 qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Fo,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return kt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=ol(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Y=s.events[ne][1].type;if(Y==="lineEnding"||Y==="linePrefix")ne--;else break}const F=ne>-1?s.events[ne][1].type:null,G=F==="tableHead"||F==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):xt(B)?kt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,xt(B)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return xt(B)?kt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?te(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),j(B)):q(B)}function j(B){return B===45?(e.consume(B),j):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return xt(B)?kt(e,te,"whitespace")(B):te(B)}function te(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ie(B)}function ie(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ie):B===null||Ye(B)?(e.exit("tableRow"),t(B)):xt(B)?kt(e,ie,"whitespace")(B):(e.enter("data"),fe(B))}function fe(B){return B===null||B===124||qt(B)?(e.exit("data"),ie(B)):(e.consume(B),B===92?be:fe)}function be(B){return B===92||B===124?(e.consume(B),fe):fe(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,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 Qv(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 S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Ye(p)?t(p):xt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const la=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],cl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...la,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...la],h2:[["className","sr-only"]],img:[...la,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...la,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...la],table:[...la],ul:[...la,["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"]},Ls={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...cl,...t}:cl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Wo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Wo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Ls.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const sl=["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"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(sl.map(e=>[IS(e),e])),P3={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 yu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function _m(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=_m(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 Co(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,j=Math.max(1,_-E),I=a.fontWeight??400,te=iy((ie,fe)=>e(ie,fe,I),t,f,N),q=te.length*N*o,R=te.every(ie=>e(ie,N,I)<=f+.5);return{lines:te,ok:q<=j&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function jr(e,t,i){return Math.min(i,Math.max(t,e))}function al(e,t,i){return typeof e=="number"&&Number.isFinite(e)?jr(e,t,i):void 0}function bm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=al(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=al(t.lineHeightFactor,.9,2),c=al(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 Wu(e){if(!e||typeof e!="object")return;const t=e,i=al(t.paddingX,0,.25),s=al(t.paddingY,0,.25),a=al(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 ko(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=bm(e.textStyle),h=Wu(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 $S(e,t,i){const s=Wu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?jr(e,h,p):t+i/2,half:c}}function vm(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:j,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:j-I,y:E},base2:{x:j+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:vm(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Bp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 cu=.05;function $i(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?cu:jr(o?1-t-cu:(1-t)/2,0,1),_=c?cu:jr(h?1-i-cu:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=$i(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=$i(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if($i(t.x)&&$i(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=jr(c,0,1),h=jr(h,0,1),a=jr(a,.02,1),o=jr(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&$i(b.x)&&$i(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=bm(t.textStyle),x=Wu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&$i(t.x)&&$i(t.y)&&$i(t.width)&&$i(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=bm(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=Wu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return $i(e==null?void 0:e.x)&&$i(e==null?void 0:e.y)&&$i(e==null?void 0:e.width)&&$i(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function dn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||dn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function uu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(uu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(uu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(uu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(uu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function ym(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Df=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Df.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=[...Df.map(c=>c.key),"other"],a=c=>{var h;return((h=Df.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:aD(h)})}return o}const lD=220,Mf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function Sm(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)||Mf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Mf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Mf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Lp(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)dn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 _o(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Lp(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.total,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(j=>!_[j]),v=j=>s.needClean>0?_o(j,s.needClean):"no image cuts",S={plan:_o(s.total,s.total),clean:v(s.withClean),letter:_o(s.withText,s.total),export:_o(s.exported,s.total),upload:_o(s.uploaded,s.total),publish:null},N=x.map((j,I)=>({key:j,label:cD[j],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},wm=[{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:[]}],bD="system-ui, sans-serif",vD=wm.find(e=>e.family==="Noto Sans"),yD=wm.find(e=>e.category==="display");function QS(e){return wm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Mu(e){return`"${e.family}", ${bD}`}function SD(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 nl(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==nl(e.current)}function Cm(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=Cm(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Bp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function kn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const Su={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Bf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:Su[e.type]}const py=.05,ED=[{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 hu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,hi,Lt,yt,Dt,Qe,di;const b=QS(c),v=JS(),S=Mu(b),N=Mu(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let H=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Se}=await uy(async()=>{const{ensureFontsReady:Oe}=await import("./export-cut-BuLQ0Lx7.js");return{ensureFontsReady:Oe}},[]);await Se([b.family,v.family])}catch{}H||G(!0)})(),()=>{H=!0}},[b.family,v.family]);const M=_m(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),j=E.invalid.length,[I,te]=w.useState(!1),q=j===0&&E.changed&&E.overlays.length>0,[R,ie]=w.useState(()=>E.overlays),[fe,be]=w.useState(()=>nl(E.overlays)),B=w.useRef(null),ne=w.useCallback(H=>(Se,Oe,Ae=400)=>{var Fe;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Fe=B.current)==null?void 0:Fe.getContext("2d");return Ge?(Ge.font=`${Ae} ${Oe}px ${H}`,Ge.measureText(Se).width):Se.length*Oe*.5},[]),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(!1),[$,ge]=w.useState(!1),[T,D]=w.useState(null),[K,C]=w.useState(null),[X,re]=w.useState({x:0,y:0,width:0,height:0}),le=w.useRef(null),V=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const H=le.current;if(!H)return;const Se=H.clientWidth,Oe=H.clientHeight;let Ae,Ge;if(t.kind==="text"){const ct=YS(t.aspectRatio)??{width:800,height:600};Ae=ct.width,Ge=ct.height}else{const ct=V.current;if(!ct||!ct.naturalWidth)return;Ae=ct.naturalWidth,Ge=ct.naturalHeight}if(!Se||!Oe)return;const Fe=Math.min(Se/Ae,Oe/Ge),dt=Ae*Fe,ft=Ge*Fe;re({x:(Se-dt)/2,y:(Oe-ft)/2,width:dt,height:ft})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=le.current;if(!H)return;const Se=new ResizeObserver(()=>_e());return Se.observe(H),()=>Se.disconnect()},[_e]);const Me=w.useCallback(H=>{const Se=WS(H.type,H.x,H.y),Oe=Se.width,Ae=Math.max(.08,1-H.y);if(!H.text||!F||X.width<=0)return Se;const Ge=H.type==="sfx"?N:S,Fe=kn(Oe,X.width);let dt=H.type==="sfx"?.08:.12;for(let ft=0;ft<24;ft++){const ct=Math.min(dt,Ae),Kt=kn(ct,X.height);if(!Co(ne(Ge),H.text,Fe,Kt,ko({...H},X.height||300,Fe,Kt)).overflow||ct>=Ae)return{width:Oe,height:ct};dt+=.03}return{width:Oe,height:Math.min(dt,Ae)}},[F,X,ne,S,N]),Le=w.useCallback(H=>{const Se=Bp(H,.1+Math.random()*.3,.1+Math.random()*.3),Oe={...Se,...Me(Se)};ie(Ae=>[...Ae,Oe]),U(Oe.id)},[Me]),He=w.useCallback(H=>{const Oe={...Bp(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},Ae={...Oe,...Me(Oe)};ie(Ge=>[...Ge,Ae]),U(Ae.id)},[Me]),Ce=w.useCallback((H,Se)=>{ie(Oe=>Oe.map(Ae=>Ae.id===H?{...Ae,...Se}:Ae))},[]),Ue=w.useCallback(H=>{var dt;const Se=X.height||300,Oe=X.width>0?kn(H.width,X.width):200,Ae=X.height>0?kn(H.height,X.height):100,Ge=H.type==="sfx"?N:S,Fe=Co(ne(Ge),H.text,Oe,Ae,ko({...H,textStyle:void 0},Se,Oe,Ae));Ce(H.id,{textStyle:{mode:"manual",fontScale:Fe.fontSize/Math.max(1,Se),fontWeight:((dt=H.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Fe.fontSize>0?Fe.lineHeight/Fe.fontSize:1.2,speakerScale:Fe.fontSize>0&&Fe.speakerFontSize>0?Fe.speakerFontSize/Fe.fontSize:.8}})},[X,N,S,ne,Ce]),et=w.useCallback(H=>{ie(Se=>Se.filter(Oe=>Oe.id!==H)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),Ke=w.useCallback((H,Se)=>{H.stopPropagation(),U(Se),z(!1)},[]),Et=w.useCallback((H,Se,Oe)=>{H.stopPropagation(),H.preventDefault();const Ae=R.find(Ge=>Ge.id===Se);Ae&&(U(Se),he.current={id:Se,mode:Oe,startX:H.clientX,startY:H.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const H=Oe=>{const Ae=he.current;if(!Ae||X.width===0)return;const Ge=dy(Oe.clientX-Ae.startX,X.width),Fe=dy(Oe.clientY-Ae.startY,X.height);if(Ae.mode==="move"){const dt=hu(Ae.origX+Ge,0,1-Ae.origW),ft=hu(Ae.origY+Fe,0,1-Ae.origH);Ce(Ae.id,{x:dt,y:ft})}else{const dt=hu(Ae.origW+Ge,py,1-Ae.origX),ft=hu(Ae.origH+Fe,py,1-Ae.origY);Ce(Ae.id,{width:dt,height:ft})}},Se=()=>{he.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",Se),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",Se)}},[X,Ce]);const ze=w.useCallback(async()=>{var H;C(null);try{const Se=nl(R),Oe=((H=t.aiDraft)==null?void 0:H.status)==="generated"&&Se!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Oe??null),f&&a()}catch(Se){C(Se instanceof Error?Se.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),_t=w.useCallback(async()=>{if(j>0&&!I){const H=j;D(`${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}ge(!0),D(null);try{await s(R);const{exportCut:H,ensureFontsReady:Se}=await uy(async()=>{const{exportCut:pt,ensureFontsReady:qi}=await import("./export-cut-BuLQ0Lx7.js");return{exportCut:pt,ensureFontsReady:qi}},[]),Oe=R.some(pt=>pt.type==="sfx"),Ae=[b.family,...Oe?[v.family]:[]],{ready:Ge,missing:Fe}=await Se(Ae);if(!Ge){D(`Fonts not loaded: ${Fe.join(", ")}. Check your connection and retry.`),ge(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),ge(!1);return}const dt=M.url,ft=await H(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),ct=new FormData,Kt=ft.type==="image/webp"?"webp":"jpg";ct.append("file",ft,`cut-${t.id}.${Kt}`);const Ei=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:ct});if(Ei.ok)be(nl(R)),o==null||o();else{const pt=await Ei.json();D(pt.error||"Export failed")}}catch(H){D(H instanceof Error?H.message:"Export failed")}finally{ge(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,j,I]),Te=R.find(H=>H.id===Y),Vt=w.useMemo(()=>X3(R),[R]),ki=w.useRef(t.id);w.useEffect(()=>{ki.current!==t.id&&(ki.current=t.id,be(nl(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:R}),tt=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),Q=w.useMemo(()=>Cm(t),[t]),xe=w.useMemo(()=>{const H={};for(const Se of R){const Oe=F3(Se);let Ae=!1;if(F&&X.width>0&&Se.text){const Ge=Se.type==="sfx"?N:S,Fe=kn(Se.width,X.width),dt=kn(Se.height,X.height);Ae=Co(ne(Ge),Se.text,Fe,dt,ko(Se,X.height||300,Fe,dt)).overflow}(Oe||Ae)&&(H[Se.id]={outOfBounds:Oe,overflow:Ae})}return H},[R,F,X,ne,S,N]),je=Object.keys(xe).length,$e=t.kind==="text",nt=!t.cleanImagePath;return!$e&&nt&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"}),d.jsx("button",{onClick:()=>Le("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"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),K&&d.jsx("span",{className:"text-[10px] text-error",children:K}),d.jsx("button",{onClick:_t,disabled:$,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:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{ze()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),j>0&&!I?d.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:[d.jsxs("span",{children:[j," overlay",j===1?"":"s"," ","from the cut plan ",j===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",j===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",j," unplaceable overlay",j===1?"":"s"]})]}):j>0?d.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 ",j," unplaceable overlay",j===1?"":"s"," — the export will not include"," ",j===1?"it":"them","."]}):q?d.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,Vt.length>0&&d.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,": ",Vt.length," bubble"," ",Vt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Vt.map(H=>`#${H.indexA+1} ${Bf(R[H.indexA])} ↔ #${H.indexB+1} ${Bf(R[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",tt.hasCleanImage],["script-text","Script text",tt.hasScriptText],["bubbles",`Bubbles placed${tt.bubblesPlaced?` (${tt.bubblesPlaced})`:""}`,tt.bubblesPlaced>0],["exported","Final exported",tt.exported],["uploaded","Uploaded",tt.uploaded]].map(([H,Se,Oe])=>d.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Oe?"true":"false",className:`flex items-center gap-1 ${Oe?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Oe?"✓":"○"}),Se]},H))}),Ct&&d.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."}),je>0&&d.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:[je," bubble",je===1?"":"s"," may not export cleanly:"," ",Object.entries(xe).map(([H,Se])=>{const Oe=R.findIndex(Ge=>Ge.id===H),Ae=[Se.outOfBounds?"outside image":null,Se.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Oe+1} ${Bf(R[Oe])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:le,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:V,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):$e?X.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:X.x,top:X.y,width:X.width,height:X.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&X.width===0){const Se=H.getBoundingClientRect();Se.width>0&&re({x:0,y:0,width:Se.width,height:Se.height})}},children:"Narration cut"}),X.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(H=>{if(H.type!=="speech")return null;const Se=X.x+kn(H.x,X.width),Oe=X.y+kn(H.y,X.height),Ae=kn(H.width,X.width),Ge=kn(H.height,X.height),Fe=$S(H,Ae,Ge),dt=H.tailAnchor?vm(Se,Oe,Ae,Ge,H.tailAnchor,Fe):null,ft=Math.max(1.5,X.height*.004),ct=H.id===Y;return d.jsx("path",{"data-testid":`balloon-${H.id}`,d:qS(Se,Oe,Ae,Ge,dt,Fe),className:`fill-white/95 ${ct?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:ct?ft+.5:ft,strokeLinejoin:"round"},H.id)})}),X.width>0&&R.map(H=>{const Se=X.x+kn(H.x,X.width),Oe=X.y+kn(H.y,X.height),Ae=kn(H.width,X.width),Ge=kn(H.height,X.height),Fe=H.id===Y,dt=H.type==="speech",ft=H.type==="narration",ct=!!xe[H.id];return d.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":ct?"true":"false",onClick:Kt=>Ke(Kt,H.id),onMouseDown:Kt=>Et(Kt,H.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[H.type]}`} ${ft?"bg-[#f4efe6]/85 rounded-md":""} ${Fe&&!dt?"ring-2 ring-accent":""} ${ct?"ring-2 ring-amber-500":""}`,style:{left:Se,top:Oe,width:Ae,height:Ge},children:[(()=>{var qi,jn;const Kt=H.type==="sfx"?N:S;if(!H.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Kt},children:Su[H.type]});const Ei=H.type!=="sfx"&&!!H.speaker;if(!F)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Kt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((qi=H.textStyle)==null?void 0:qi.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:Ei?`${H.speaker}: ${H.text}`:H.text});const pt=Co(ne(Kt),H.text,Ae,Ge,ko(H,X.height,Ae,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Kt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[Ei&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:pt.speakerFontSize,lineHeight:1.2},children:H.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:pt.fontSize,lineHeight:`${pt.lineHeight}px`,fontWeight:((jn=H.textStyle)==null?void 0:jn.fontWeight)??400},children:pt.lines.map((sn,Fn)=>d.jsx("span",{className:"block",children:sn},Fn))})]})})(),Fe&&d.jsx("div",{onMouseDown:Kt=>{Kt.stopPropagation(),Et(Kt,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)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((hi=t.aiDraft)==null?void 0:hi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(H=>d.jsxs("button",{onClick:()=>He(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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",Su[H.type]]})," ",d.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:Su[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:H=>Ce(Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:H=>Ce(Te.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"})]}),d.jsx("button",{onClick:()=>Ce(Te.id,Me(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Lt=Te.textStyle)==null?void 0:Lt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>Ce(Te.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"}):d.jsx("button",{type:"button",onClick:()=>Ue(Te),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"})]}),((yt=Te.textStyle)==null?void 0:yt.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:H=>Ce(Te.id,{textStyle:{...Te.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:H=>Ce(Te.id,{textStyle:{...Te.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const H=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Se=>d.jsx("button",{type:"button",onClick:()=>Ce(Te.id,{tailAnchor:Se.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-${Se.key}`,children:Se.label},Se.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:Se=>Ce(Te.id,{tailAnchor:{...H,x:parseFloat(Se.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:Se=>Ce(Te.id,{tailAnchor:{...H,y:parseFloat(Se.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Dt=Te.bubbleStyle)==null?void 0:Dt.paddingX)??.06)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Qe=Te.bubbleStyle)==null?void 0:Qe.paddingY)??.08)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((di=Te.bubbleStyle)==null?void 0:di.cornerRadius)??.4)*100).toFixed(0),onChange:H=>Ce(Te.id,{bubbleStyle:{...Te.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?et(Te.id):z(!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:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Mu(x),S=Mu(b),N=_m(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[j,I]=w.useState(!1),[te,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,ie]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var ne;try{(ne=document.fonts)!=null&&ne.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const ne=new ResizeObserver(()=>{ie({width:B.clientWidth,height:B.clientHeight})});return ne.observe(B),()=>ne.disconnect()},[]);const fe=w.useCallback(B=>(ne,F,G=400)=>E?(E.font=`${G} ${F}px ${B}`,E.measureText(ne).width):ne.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${te.width} / ${te.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const ne=B.currentTarget.naturalWidth||te.width,F=B.currentTarget.naturalHeight||te.height;ne>0&&F>0&&q({width:ne,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=$S(B,G,Y),A=B.tailAnchor?vm(ne,F,G,Y,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(ne,F,G,Y,A,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var $;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=B.type==="sfx"?S:v,A=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${A?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:ne,top:F,width:G,height:Y},children:B.text?j?(()=>{var T;const ge=Co(fe(U),B.text,G,Y,ko(B,R.height,G,Y));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:ge.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ge.fontSize,lineHeight:`${ge.lineHeight}px`,fontWeight:((T=B.textStyle)==null?void 0:T.fontWeight)??400},children:ge.lines.map((D,K)=>d.jsx("span",{className:"block",children:D},K))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(Y*.05,14)),fontWeight:(($=B.textStyle)==null?void 0:$.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` -`).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(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(` -`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const Op=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Op)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=Op)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=Op}async function qD(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 Gu(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const j=await GD(e);E||o(j)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const j=await YD(e,E);await i(j)}catch(j){h(j instanceof Error?j.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(j=>j.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(j=>j.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(j=>j.status!=="done").length,M=p.reduce((j,I)=>j+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(j=>d.jsxs("li",{"data-testid":`finish-step-${j.key}`,"data-status":j.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${j.status==="current"?"border-accent/40 bg-accent/10 text-accent":j.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[j.status]}),d.jsx("span",{children:j.label}),j.detail&&d.jsxs("span",{className:"text-muted",children:["· ",j.detail]})]},j.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(j=>d.jsxs("div",{"data-testid":`finish-issue-group-${j.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:j.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:j.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},j.key))})]})]})]})}function tM(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 Ao(e){return(!!e.cleanImagePath||dn(e))&&Cm(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:nl(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":dn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:dn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Ao(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:dn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:j,converting:I,rowRef:te}){var He,Ce;const q=w.useRef(null),[R,ie]=w.useState(!1),[fe,be]=w.useState(null),[B,ne]=w.useState(!1),[F,G]=w.useState(!1),[Y,U]=w.useState(!1),[A,z]=w.useState(!1),$=r1(e),ge=S.length>0,T=!!E,D=w.useCallback(async()=>{E&&(z(!0),await j(e.id,E),z(!1),h())},[E,j,e.id,h]),K=w.useCallback(async Ue=>{ie(!0),be(null);try{let et=Ue;if(!n1(Ue))try{et=await Gu(Ue)}catch(ze){return be(ze instanceof Error?ze.message:"Could not import image"),!1}const at=et.type==="image/jpeg"?"jpg":"webp",Ke=new FormData;Ke.append("file",new File([et],`clean.${at}`,{type:et.type}));const Et=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ke});if(!Et.ok){const ze=await Et.json();return be(ze.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{ie(!1)}},[c,t,i,e.id,h]),C=nM(e,T,ge),X=e.cleanImagePath??E??null,re=((He=e.overlays)==null?void 0:He.length)??0,le=!dn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!ge&&!T,V=!ge&&!T&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Ao(e),he=(((Ce=e.overlays)==null?void 0:Ce.length)??0)>0?"Re-draft with AI":"AI draft lettering",_e=C.key==="convert"?{label:A?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=rM(e),Le=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||dn(e);return d.jsxs("div",{ref:te,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),X||dn(e)?d.jsx(jD,{storyName:t,assetPath:X,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Le?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:dn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[le?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:re>0?"Review lettering":"Open focused editor"}),V&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):_e?d.jsx("button",{onClick:_e.onClick,disabled:C.key==="convert"&&(A||I),"data-testid":_e.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:_e.label}):null,!le&&!_e&&V&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[T&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:A||I,"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:A?"Converting…":"Convert image"})]}),ge&&!T&&d.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:[S.map((Ue,et)=>d.jsx("p",{className:"text-[11px] text-error",children:Ue},et)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!dn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),ne(!0),setTimeout(()=>ne(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ue=>{var at;const et=(at=Ue.target.files)==null?void 0:at[0];et&&K(et),Ue.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var Ue;return(Ue=q.current)==null?void 0:Ue.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(Ue=>!Ue),disabled:R,"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:Y?"Hide Codex images":"Import from Codex"})]}),Y&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async Ue=>{await K(Ue)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.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."}),$==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!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:F?"Copied!":"Copy Codex task"})]}),$==="missing"&&f&&d.jsx("button",{onClick:_,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"}),fe&&d.jsx("p",{className:"text-xs text-error mt-1",children:fe})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||dn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ue,et)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[Ue.speaker,":"]})," ",Ue.text]},et))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var mr,Ot,oe;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,j]=w.useState(null),[I,te]=w.useState(null),[q,R]=w.useState(null),[ie,fe]=w.useState(!1),[be,B]=w.useState([]),[ne,F]=w.useState(!1),[G,Y]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[C,X]=w.useState(null),[re,le]=w.useState(null),[V,he]=w.useState(null),[_e,Me]=w.useState(!1),[Le,He]=w.useState(new Set),[Ce,Ue]=w.useState(new Map),[et,at]=w.useState(!1),[Ke,Et]=w.useState(null),[ze,_t]=w.useState(!1),[Te,Vt]=w.useState(null),ki=w.useRef(new Map),Ct=w.useRef(null),tt=t.replace(/\.md$/,"");w.useEffect(()=>{var O;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(te(c.cutId),Vt(c.cutId)),(O=S.current)==null||O.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ce;if(Te==null)return;const O=ki.current.get(Te);O&&((ce=O.scrollIntoView)==null||ce.call(O,{behavior:"smooth",block:"center"}),Vt(null))},[Te,x]);const Q=w.useCallback(async()=>{var O;try{const ce=await i(`/api/stories/${e}/cuts/${tt}`);if(ce.status===404){b(null);return}if(!ce.ok){const De=await ce.json();j(De.error||"Failed to load cuts");return}const ke=await ce.json();b(ke),j(null);try{const De=await i(`/api/stories/${e}/${t}`);if(De.ok){const Ee=await De.json(),Pe=typeof(Ee==null?void 0:Ee.content)=="string"?Ee.content:"",We=Array.isArray(ke==null?void 0:ke.cuts)?ke.cuts:[],rt=Pe.length>0&&KS(Pe,We).ready,Xe=(Ee==null?void 0:Ee.status)==="published"||(Ee==null?void 0:Ee.status)==="published-not-indexed";A({markdownReady:rt,published:Xe})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(O=v.current)==null||O.call(v)}catch{j("Failed to load cuts")}finally{M(!1)}},[i,e,tt,t]),xe=w.useCallback(async O=>!!(await i(`/api/stories/${e}/cuts/${tt}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok,[i,e,tt]),je=w.useCallback(async()=>{at(!1);try{const O=await i(`/api/stories/${e}/cuts/${tt}/detect-clean-images`);if(!O.ok)return;const ce=await O.json();He(new Set(Array.isArray(ce.detected)?ce.detected:[]));const ke=new Map,De=ce.stale;if(Array.isArray(De))for(const Ee of De){if(typeof(Ee==null?void 0:Ee.cutId)!="number"||typeof(Ee==null?void 0:Ee.message)!="string")continue;const Pe=ke.get(Ee.cutId)??[];Pe.push(Ee.message),ke.set(Ee.cutId,Pe)}Ue(ke),at(!0)}catch{}},[i,e,tt]),$e=w.useCallback(async()=>{Et(null);try{const O=await i(`/api/stories/${e}/cuts/${tt}/asset-diagnostics`);if(!O.ok)return;const ce=await O.json();Et(Array.isArray(ce.diagnostics)?ce.diagnostics:null)}catch{}},[i,e,tt]),nt=w.useCallback(async()=>{_t(!0);try{await Promise.all([Q(),je(),$e()])}finally{_t(!1)}},[Q,je,$e]),Wt=w.useCallback(async(O,ce={})=>{var Ee;if(!x)return!1;const ke=x.cuts.find(Pe=>Pe.id===O);if(!ke||!Ao(ke)||(((Ee=ke.overlays)==null?void 0:Ee.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const De=hy(ke);if(De.length===0)return le(`Cut ${ke.id}: no script lines available to draft.`),!1;he(O),le(null);try{const Pe={...x,cuts:x.cuts.map(rt=>rt.id===O?{...rt,overlays:De,aiDraft:_y(De)}:rt)};return await xe(Pe)?(le(`Cut ${ke.id}: AI draft ready`),await Q(),ce.openEditor&&R(O),!0):(le(`Cut ${ke.id}: AI draft failed`),!1)}finally{he(null)}},[x,xe,Q]),hi=w.useCallback(async()=>{if(!x)return;const O=x.cuts.filter(ce=>{var ke;return Ao(ce)&&(((ke=ce.overlays)==null?void 0:ke.length)??0)===0&&!ce.finalImagePath&&!ce.uploadedCid&&!ce.uploadedUrl});if(O.length===0){le("No unlettered cuts need an AI draft");return}Me(!0),le(null);try{const ce={...x,cuts:x.cuts.map(De=>{if(!O.some(Pe=>Pe.id===De.id))return De;const Ee=hy(De);return Ee.length>0?{...De,overlays:Ee,aiDraft:_y(Ee)}:De})};if(!await xe(ce)){le("AI draft failed");return}le(`AI draft ready for ${O.length} cut${O.length===1?"":"s"}`),await Q()}finally{Me(!1)}},[x,xe,Q]),Lt=w.useCallback(async()=>{$(!0),le(null),B([]);try{const O=await i(`/api/stories/${e}/cuts/${tt}/sync-clean-images`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Sync failed");else{const ke=Array.isArray(ce.synced)?ce.synced.length:0,De=Array.isArray(ce.cleared)?ce.cleared.length:0,Ee=Array.isArray(ce.rejected)?ce.rejected:[];Ee.length>0&&B(Ee.map(We=>`Cut ${We.cutId}: ${We.reason}`));const Pe=[];ke>0&&Pe.push(`Synced ${ke}`),De>0&&Pe.push(`Cleared ${De} stale path${De===1?"":"s"}`),le(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await je(),await $e()}}catch{le("Sync failed")}$(!1)},[i,e,tt,Q,je,$e]),yt=w.useCallback(async(O,ce)=>{try{const ke=await i(HS(e,ce));if(!ke.ok)return!1;const De=await ke.blob(),Ee=await Gu(new File([De],"clean.png",{type:De.type||"image/png"})),Pe=Ee.type==="image/jpeg"?"jpg":"webp",We=new FormData;return We.append("file",new File([Ee],`clean.${Pe}`,{type:Ee.type})),(await i(`/api/stories/${e}/cuts/${tt}/upload-clean/${O}`,{method:"POST",body:We})).ok}catch{return!1}},[i,e,tt]),Dt=w.useCallback(async O=>{K(!0),X(null);let ce=0;const ke=[];for(const De of O)await yt(De.cutId,De.pngPath)?ce++:ke.push(De.cutId);await nt(),K(!1),X(ke.length===0?`Converted ${ce} image${ce===1?"":"s"} to WebP`:`Converted ${ce}; ${ke.length} failed (Cut ${ke.join(", ")}) — try Convert image on each`)},[yt,nt]),Qe=w.useCallback(async()=>{var Ee;if(!x)return;F(!0),Y(""),B([]);const O=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),ce=[],ke=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>Y(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Jt.ok){const{cid:qn,url:xr}=await Jt.json();return{ok:!0,status:Jt.status,cid:qn,url:xr}}const Wi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:Wi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:Wi,waitMs:qn})=>Y(`Cut ${We.id} rate-limited — waiting ${Math.round(qn/1e3)}s before retry ${Jt}/${Wi}...`)});if(!Gt.ok){ce.push(`Cut ${We.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Mt,url:Ni}=Gt;(await i(`/api/stories/${e}/cuts/${tt}/set-uploaded/${We.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Mt,url:Ni})})).ok||ce.push(`Cut ${We.id}: failed to record upload`)}catch(rt){ce.push(`Cut ${We.id}: ${rt instanceof Error?rt.message:"failed"}`)}}if(ce.length>0){B(ce),F(!1),Y(""),Q();return}Y("Preparing episode for publishing…");const De=await i(`/api/stories/${e}/cuts/${tt}/generate-markdown`,{method:"POST"});if(De.ok){const Pe=await De.json();((Ee=Pe.warnings)==null?void 0:Ee.length)>0&&B(Pe.warnings)}F(!1),Y(""),Q()},[x,i,e,tt,a,Q]),di=w.useCallback(async()=>{T(!0),le(null);try{const O=await i(`/api/stories/${e}/cuts/${tt}/repair-asset-paths`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Repair failed");else{const ke=Array.isArray(ce.cleared)?ce.cleared.length:0;le(ke>0?`Cleared ${ke} stale path${ke===1?"":"s"}`:"No stale paths to clear"),await Q(),await je()}}catch{le("Repair failed")}T(!1)},[i,e,tt,Q,je]),[H,Se]=w.useState(!1),Oe=w.useCallback(async(O,ce=!0)=>{if(x){Se(!0);try{const ke=x.cuts.reduce((rt,Xe)=>Math.max(rt,Xe.id),0)+1,De={id:ke,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"},Ee=[...x.cuts];Ee.splice(Math.max(0,Math.min(O,Ee.length)),0,De);const Pe={...x,cuts:Ee},We=await i(`/api/stories/${e}/cuts/${tt}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(We.ok)ce?R(ke):te(ke),await Q();else{const rt=await We.json().catch(()=>({}));le(rt.error||"Could not add text panel")}}catch{le("Could not add text panel")}Se(!1)}},[x,i,e,tt,Q]),Ae=w.useCallback(()=>Oe((x==null?void 0:x.cuts.length)??0,!0),[Oe,x]);if(w.useEffect(()=>{Q(),je(),$e()},[Q,je,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[tt,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(O=>O.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:tt,language:s,authFetch:i,targetLabel:dn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(O,ce)=>{const ke={...x,cuts:x.cuts.map(Ee=>Ee.id===q?{...Ee,overlays:O,aiDraft:ce??Ee.aiDraft??null}:Ee)};if(!await xe(ke))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{R(null),Q()}});const Fe=x.cuts.reduce((O,ce)=>{const ke=r1(ce);return O[ke]++,O},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(O=>!dn(O)).length,ft=x.cuts.filter(O=>GS(O)).map(O=>O.id),ct=uD({cuts:x.cuts,published:U.published}),Kt=((mr=ct.steps.find(O=>O.key==="upload"))==null?void 0:mr.status)==="done",Ei=x.cuts.some(O=>O.finalImagePath&&!O.uploadedCid)||Kt&&!U.markdownReady,pt=(Ke??[]).filter(O=>O.state==="needs-conversion"&&O.convertiblePng).map(O=>({cutId:O.cutId,pngPath:O.convertiblePng})),qi=new Map(pt.map(O=>[O.cutId,O.pngPath])),jn=(Ke??[]).filter(O=>O.state==="needs-conversion"&&O.issue).map(O=>O.issue),sn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Ot=tt.match(/\d+/))==null?void 0:Ot[0])??"0",10)+1}`,Fn=typeof x.title=="string"?x.title:null,an=x.cuts.filter(O=>!dn(O)),gn={cuts:x.cuts.length,artwork:an.filter(O=>O.cleanImagePath||qi.has(O.id)).length,converted:an.filter(O=>O.cleanImagePath&&/\.(webp|jpe?g)$/i.test(O.cleanImagePath)).length,lettered:x.cuts.filter(O=>{var ce;return(((ce=O.overlays)==null?void 0:ce.length)??0)>0||!!O.finalImagePath}).length,uploaded:x.cuts.filter(O=>O.uploadedCid||O.uploadedUrl).length},ln=x.cuts.filter(O=>{var ce;return Ao(O)&&(((ce=O.overlays)==null?void 0:ce.length)??0)===0&&!O.finalImagePath&&!O.uploadedCid&&!O.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:sn}),Fn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Fn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[gn.cuts," cuts · ",gn.artwork," artwork found ·"," ",gn.converted," converted · ",gn.lettered," ","lettered · ",gn.uploaded," uploaded"]})]}),ln>0&&d.jsx("button",{onClick:hi,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${ln})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Fe.missing>0&&d.jsxs("span",{className:"text-muted",children:[Fe.missing," missing"]}),Fe.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.clean," clean"]}),Fe.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Fe.lettered," lettered"]}),Fe.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.uploaded," uploaded"]}),Fe.text>0&&d.jsxs("span",{className:"text-accent",children:[Fe.text," text ",Fe.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),B([]);try{const O=await i(`/api/stories/${e}/cuts/${tt}/generate-markdown`,{method:"POST"});if(O.ok){const ce=await O.json();B(ce.warnings||[])}}catch{}fe(!1)},disabled:ie,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:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:H,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:H?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:nt,disabled:ze,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:ze?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Lt,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"}),d.jsx("button",{onClick:Qe,disabled:ne||!(x!=null&&x.cuts.some(O=>O.finalImagePath&&!O.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),ft.length>0&&d.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:[ft.length===1?"Cut":"Cuts"," ",ft.join(", ")," ",ft.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",ft.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),et&&dt>0&&Fe.missing===0&&Ce.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),re&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:re}),pt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[pt.length," PNG image",pt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Dt(pt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),jn.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:jn.map((O,ce)=>d.jsx("li",{children:O},ce))})]})]}),Ke&&Ke.length>0&&(()=>{const O=tM(Ke),ce=Ke.filter(ke=>ke.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",O.uploaded," uploaded · ",O.finalReady," final ·"," ",O.cleanReady," clean · ",O.planned," planned",O.needsConversion>0?` · ${O.needsConversion} needs conversion`:"",O.missing>0?` · ${O.missing} missing`:""]}),ce.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ce.map(ke=>d.jsx("li",{children:ke.issue},ke.cutId))})]})})(),d.jsx(eM,{checklist:ct,issues:be,onFinish:Qe,finishing:ne,progressText:G,canFinish:Ei,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((O,ce)=>{var ke;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ce,beforeLabel:ce===0?"Episode opening":`After cut ${(ke=x.cuts[ce-1])==null?void 0:ke.id}`,afterLabel:`Before cut ${O.id}`,disabled:H,onAdd:()=>Oe(ce)}),d.jsx(sM,{cut:O,storyName:e,plotFile:tt,language:s,expanded:I===O.id,onToggle:()=>te(I===O.id?null:O.id),authFetch:i,onUpdated:()=>{Q(),je(),$e()},onOpenEditor:()=>R(O.id),detectedLocalClean:Le.has(O.id),onSyncClean:Lt,syncing:z,onAiDraft:()=>{Wt(O.id,{openEditor:!0})},aiDrafting:V===O.id,staleMessages:Ce.get(O.id)??[],onRepairStale:di,repairing:ge,conversionPng:qi.get(O.id)??null,onConvert:yt,converting:D,rowRef:De=>{De?ki.current.set(O.id,De):ki.current.delete(O.id)}})]},O.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(oe=x.cuts[x.cuts.length-1])==null?void 0:oe.id}`,afterLabel:"Episode ending",disabled:H,onAdd:()=>Oe(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 zp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function zo(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 dM(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 Pp(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 km(e){var s;const t=zp(e.fileContent);if(t)return!Pp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Pp(i)}function Em(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=zp(i);if(t==="genesis.md"){const p=a?zp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Lf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Of(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=Of(e.requiredBalance)??Of(e.creationFee),i=Of(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 _M={...cl,attributes:{...cl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E}){const[j,I]=w.useState(null),[te,q]=w.useState(!1),[R,ie]=w.useState("preview"),[fe,be]=w.useState("publish"),[B,ne]=w.useState("text"),[F,G]=w.useState(null),Y=w.useCallback((se,ye)=>{ie("edit"),G(Ne=>({cutId:se,openEditor:ye,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[U,A]=w.useState(""),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[C,X]=w.useState(null),[re,le]=w.useState(""),[V,he]=w.useState(""),[_e,Me]=w.useState(!1),[Le,He]=w.useState(null),[Ce,Ue]=w.useState(0),[et,at]=w.useState(0),[Ke,Et]=w.useState(null),[ze,_t]=w.useState(null),[Te,Vt]=w.useState(null),[ki,Ct]=w.useState(0),tt=w.useRef(null),Q=w.useRef(!1),[xe,je]=w.useState(!1),[$e,nt]=w.useState(sl[0]),[Wt,hi]=w.useState(ts[0]),[Lt,yt]=w.useState(!1),[Dt,Qe]=w.useState(null),[di,H]=w.useState(null),[Se,Oe]=w.useState(!1),[Ae,Ge]=w.useState(!1),[Fe,dt]=w.useState(!1),[ft,ct]=w.useState(null),[Kt,Ei]=w.useState(!1),pt=w.useRef(null),qi=w.useRef(null),[jn,sn]=w.useState(!1),[Fn,an]=w.useState(null),[gn,ln]=w.useState(null),[mr,Ot]=w.useState("unknown"),oe=w.useRef(!1),[O,ce]=w.useState(!1),[ke,De]=w.useState(!1),[Ee,Pe]=w.useState(null),[We,rt]=w.useState([]),[Xe,Nt]=w.useState(null),jt=w.useRef(null),Gt=w.useRef(null),Mt=w.useCallback(async()=>{if(!e||!t){I(null);return}const se=`${e}/${t}`,ye=Gt.current!==se;ye&&(Gt.current=se);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Je=await Ne.json();I(Je),(ye||!Q.current)&&(A(Je.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{q(!0),Mt().finally(()=>q(!1))},[Mt]),w.useEffect(()=>{if(!e||!t||R==="edit"&&ge)return;const se=setInterval(Mt,3e3);return()=>clearInterval(se)},[e,t,Mt,R,ge]);const[Ni,gr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){gr(null);return}let se=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{se||gr(ye?Lp(ye.cuts||[]):null)}).catch(()=>{se||gr(null)}),()=>{se=!0}},[Jt,e,i]);const Wi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!Wi||!e||!t){He(null),Ue(0),at(0),Et(null);return}let se=!1;const ye=t.replace(/\.md$/,"");return Et(null),(async()=>{try{const[Ne,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(se)return;if(!Je.ok){He("error"),Ue(0),at(0),Et(null);return}const Tt=await Je.json(),xi=Tt.cuts||[],Yn=Ne.ok?(await Ne.json()).content??"":"",Or=XS(Yn,xi);se||(He(Or.stage),Ue(Or.awaitingCount),at(Or.totalCuts),Et(Lp(xi)),Vt(typeof Tt.title=="string"?Tt.title:null))}catch{se||(He("error"),Ue(0),at(0),Et(null))}})(),()=>{se=!0}},[Wi,e,t,i,j==null?void 0:j.content,j==null?void 0:j.status,ki]),w.useEffect(()=>{if(!e){_t(null);return}let se=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{se||_t((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{se=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const se=yu(p);let ye=se??"";if(!se&&ze){const Je=ze.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(ye=yu(Je[1].replace(/\*+/g,"").trim())??"")}le(ye);let Ne=h&&ts.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!Ne&&ze){const Je=ze.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(Ne=ts.find(Tt=>Tt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(Ne),Me(f??!1)},[e,p,h,f,ze]);const qn=w.useCallback(se=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}).catch(()=>{})},[e,i]),xr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]);w.useCallback(async()=>{if(!e||!t)return;const se=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${se}/generate-markdown`,{method:"POST"})).ok&&(await Mt(),Ct(Ne=>Ne+1))}catch{}},[e,t,i,Mt]);const ei=w.useCallback(se=>{var Je;const ye=(Je=se.target.files)==null?void 0:Je[0];if(!ye)return;oe.current=!0,an(null),ln(null);const Ne=Sy(ye);if(Ne){Qe(null),H(Tt=>(Tt&&URL.revokeObjectURL(Tt),null)),pt.current&&(pt.current.value=""),ct(Ne),Ot("invalid");return}Qe(ye),H(Tt=>(Tt&&URL.revokeObjectURL(Tt),URL.createObjectURL(ye))),ct(null),Ot("selected")},[]),Dr=w.useCallback(async se=>{var Ne;const ye=(Ne=se.target.files)==null?void 0:Ne[0];if(qi.current&&(qi.current.value=""),!(!ye||!e)){oe.current=!0,an(null),sn(!0),ct(null);try{let Je;try{Je=await Gu(ye)}catch(Vn){Qe(null),H(Us=>(Us&&URL.revokeObjectURL(Us),null)),ct(Vn instanceof Error?Vn.message:"Could not import image");return}const Tt=Je.type==="image/jpeg"?"jpg":"webp",xi=new File([Je],`cover.${Tt}`,{type:Je.type}),Yn=new FormData;Yn.append("file",xi);const Or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Yn});if(!Or.ok){const Vn=await Or.json().catch(()=>({}));ct(Vn.error||"Cover import failed");return}Qe(xi),H(Vn=>(Vn&&URL.revokeObjectURL(Vn),URL.createObjectURL(xi))),ln(null),Ot("selected"),ct(null)}catch{ct("Cover import failed")}finally{sn(!1)}}},[e,i]),Tn=w.useCallback(async se=>{if(se.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(se.type)){Pe("Only WebP and JPEG images are accepted");return}De(!0),Pe(null);try{const Ne=new FormData;Ne.append("file",se);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Je.ok){const xi=await Je.json();throw new Error(xi.error||"Upload failed")}const Tt=await Je.json();rt(xi=>[...xi,{cid:Tt.cid,url:Tt.url}])}catch(Ne){Pe(Ne instanceof Error?Ne.message:"Upload failed")}finally{De(!1),jt.current&&(jt.current.value="")}},[i]),or=w.useCallback(se=>{var Ne;const ye=(Ne=se.target.files)==null?void 0:Ne[0];ye&&Tn(ye)},[Tn]),on=w.useCallback(async()=>{if(j!=null&&j.storylineId){Oe(!0),ct(null),Ei(!1);try{let se;if(Dt){const Ne=new FormData;Ne.append("file",Dt);const Je=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Je.ok){const xi=await Je.json();throw new Error(xi.error||"Cover upload failed")}se=(await Je.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:j.storylineId,...se!==void 0&&{coverCid:se},genre:$e,language:Wt,isNsfw:Lt})});if(!ye.ok){const Ne=await ye.json();throw new Error(Ne.error||"Update failed")}Ei(!0),Qe(null),se!==void 0&&(dt(!0),H(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Ot("unknown"),pt.current&&(pt.current.value="")),setTimeout(()=>Ei(!1),3e3)}catch(se){ct(se instanceof Error?se.message:"Update failed")}finally{Oe(!1)}}},[j==null?void 0:j.storylineId,Dt,$e,Wt,Lt,i]);w.useEffect(()=>{je(!1),Qe(null),H(null),ct(null),Ei(!1),Ge(!1),ce(!1),rt([]),Pe(null),an(null),ln(null),Ot("unknown"),oe.current=!1,ne("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!j||j.storylineId||j.status==="published"||j.status==="published-not-indexed"||oe.current)return;let se=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(se||!ye.ok)return;const Ne=await ye.json();if(se)return;if(!(Ne!=null&&Ne.found)){Ot("none");return}if(!Ne.valid){ln(Ne.error||"Detected cover asset is invalid and was not used"),Ot("invalid");return}const Je=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(se||!Je.ok)return;const Tt=await Je.blob(),xi=new File([Tt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(Sy(xi)||se||oe.current)return;Qe(xi),H(Yn=>(Yn&&URL.revokeObjectURL(Yn),URL.createObjectURL(xi))),an(Ne.path),Ot("detected")}catch{}})(),()=>{se=!0}},[e,t,j,j==null?void 0:j.status,j==null?void 0:j.storylineId,i]),w.useEffect(()=>{if(!xe||!(j!=null&&j.storylineId))return;Ge(!1);const se="https://plotlink.xyz";let ye=!1;return fetch(`${se}/api/storyline/${j.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!ye){if(!Ne){ct("Could not load current story metadata");return}if(Ne.genre){const Je=yu(Ne.genre);Je&&nt(Je)}if(Ne.language){const Je=ts.find(Tt=>Tt.toLowerCase()===Ne.language.toLowerCase());Je&&hi(Je)}Ne.isNsfw!==void 0&&yt(!!Ne.isNsfw),dt(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),Ge(!0)}}).catch(()=>{ye||ct("Could not load current story metadata")}),()=>{ye=!0}},[xe,j==null?void 0:j.storylineId]),w.useEffect(()=>{if(R!=="edit")return;const se=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),xr())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[R,xr]),w.useEffect(()=>{if((j==null?void 0:j.status)!=="published-not-indexed"||!j.publishedAt)return;const se=new Date(j.publishedAt).getTime(),ye=300*1e3,Ne=()=>{const Tt=Math.max(0,ye-(Date.now()-se));X(Tt)};Ne();const Je=setInterval(Ne,1e3);return()=>clearInterval(Je)},[j==null?void 0:j.status,j==null?void 0:j.publishedAt]);const St=C!==null&&C<=0,An=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!j)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const _r=(R==="edit"?U:(j==null?void 0:j.content)??"").length,fi=t==="genesis.md",xn=t?/^plot-\d+\.md$/.test(t):!1,Mi=c==="cartoon"&&xn,ni=c==="cartoon"&&fi,Mr=ni||Mi,Br=(j==null?void 0:j.status)==="published"||(j==null?void 0:j.status)==="published-not-indexed",xa=S&&Mr,Lr=ni?Ni?Ni.total:null:Mi?Le===null?null:et:null,_a=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Br,cutCount:Lr,cutProgress:ni?Ni:null}),pl=(ni||Mi)&&!Br,Wn=pl?Em({fileName:t,fileContent:(j==null?void 0:j.content)??"",storySlug:e??"",structureContent:ze,contentType:"cartoon",episodeTitle:Te}):null,ml=!!Wn&&zo(Wn,t),gl=Mi&&!Br&&!km({fileContent:(j==null?void 0:j.content)??"",episodeTitle:Te}),as=ni&&!Br?Sm((j==null?void 0:j.content)??""):null,ba=!!as&&as.blockers.length>0,Yu="w-full max-w-[32rem] rounded-xl border px-3 py-3",Vu={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Hs=se=>{if(!ni)return null;const ye=cM({hasSelectedCover:!!Dt,invalid:mr==="invalid",attached:se});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${Vu[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},Rn=ml||gl,xl=()=>{if(!pl||!Wn)return null;const se=fi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":ml?"true":"false","data-blocked":Rn?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[se,":"]})," ",d.jsx("span",{className:Rn?"text-error font-medium":"text-foreground",children:Wn})]}),ml?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",fi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):gl?d.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]})},_l=()=>as?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":ba?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),as.blockers.map((se,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:se},`b-${ye}`)),as.warnings.map((se,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:se},`w-${ye}`))]}):null,Gn=fi||xn?1e4:null,cr=!Br&&Gn!==null&&_r>Gn,Yo=(j==null?void 0:j.content)??"",ls=Br?{count:0,warnings:[]}:yM(Yo),bl=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:tt,value:U,onChange:se=>{A(se.target.value),T(!0),Q.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:ge?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:xr,disabled:!ge||z,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!xa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(j==null?void 0:j.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(j==null?void 0:j.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:j.indexError,children:"Published (not indexed)"}),(j==null?void 0:j.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${cr?"text-error font-medium":"text-muted"}`,children:[_r.toLocaleString(),Gn!==null?`/${Gn.toLocaleString()}`:" chars"]}),cr&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(_r-Gn).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",ge&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),R==="preview"?Mi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>be("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>be("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(gD,{content:(j==null?void 0:j.content)??"",stage:Le}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:Y})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:j!=null&&j.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:j.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Mi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ct(se=>se+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):ni?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>ne("text"),className:`px-2 py-0.5 text-[11px] rounded ${B==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ne("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${B==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ct(se=>se+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):bl})]}):bl,!xa&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:_a}):(j==null?void 0:j.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!St&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!j.txHash)){K(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:j.txHash,content:j.content,storylineId:j.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:j.txHash,storylineId:j.storylineId,contentCid:"",gasCost:""})}),Mt())}catch{}K(!1)}},disabled:D,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:D?"Retrying...":`Retry Index${An?` (${An})`:""}`}),xn&&d.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,re,V,_e)},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"}),j.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${j.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:St?xn?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":xn?"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."}),j.indexError&&d.jsx("p",{className:"text-error text-xs",children:j.indexError})]}):(j==null?void 0:j.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),j.storylineId&&d.jsx("a",{href:(()=>{var Ne;const se=`https://plotlink.xyz/story/${j.storylineId}`;if(!xn)return se;const ye=j.plotIndex!=null&&j.plotIndex>0?j.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${se}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),j.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${j.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),fi&&o&&j.storylineId&&(!j.authorAddress||j.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>je(se=>!se),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:xe?"Close Edit":"Edit Story"})]}),xe&&fi&&j.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Hs(Fe),d.jsxs("div",{className:"flex items-start gap-3",children:[di&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:di,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Qe(null),H(null),ln(null),Ot("unknown"),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:ei,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:$e,onChange:se=>nt(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:sl.map(se=>d.jsx("option",{value:se,children:se},se))}),d.jsx("select",{value:Wt,onChange:se=>hi(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(se=>d.jsx("option",{value:se,children:se},se))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Lt,onChange:se=>yt(se.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:on,disabled:Se||!Ae,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Se?"Saving...":Ae?"Save Changes":"Loading..."}),Kt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),ft&&d.jsx("span",{className:"text-error text-xs",children:ft})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Mi&&Ke&&Ke.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Ke.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.withClean,"/",Ke.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.withText,"/",Ke.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ke.uploaded,"/",Ke.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),ni&&Ni&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Ni.total," planned",Ni.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Ni.withClean," clean ·"," ",Ni.withText," lettered ·"," ",Ni.exported," exported ·"," ",Ni.uploaded," uploaded"]})]}),(ni||Mi)&&_a&&d.jsxs("div",{className:`${Yu} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Lr===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:ni?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_a})]}),xn&&!Mi&&R==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:O,onChange:se=>ce(se.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),O&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 se;return(se=jt.current)==null?void 0:se.click()},onDragOver:se=>{se.preventDefault(),se.stopPropagation()},onDrop:se=>{var Ne;se.preventDefault(),se.stopPropagation();const ye=(Ne=se.dataTransfer.files)==null?void 0:Ne[0];ye&&Tn(ye)},children:[d.jsx("input",{ref:jt,type:"file",accept:"image/webp,image/jpeg",onChange:or,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:ke?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ee&&d.jsx("span",{className:"text-error text-xs",children:Ee}),We.map((se,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",se.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${se.url})`),Nt(ye),setTimeout(()=>Nt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Xe===ye?"Copied!":"Copy"})]})]},se.cid))]})]}),fi&&c!=="cartoon"&&!(R==="edit"&&B==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Hs(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[di&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:di,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{oe.current=!0,an(null),ln(null),Ot("unknown"),Qe(null),H(se=>(se&&URL.revokeObjectURL(se),null)),pt.current&&(pt.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:ei,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:qi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Dr,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var se;return(se=qi.current)==null?void 0:se.click()},disabled:jn,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:jn?"Importing…":"Import generated image (PNG ok)"}),Dt&&d.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."}),Fn&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Fn," — pick a file to override."]}),gn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[gn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&mr==="none"&&!Dt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),ft&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:ft})]})]})]}),!Mr&&xl(),!Mr&&_l(),!Mr&&d.jsxs("div",{className:"flex items-center gap-2",children:[fi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:re,"data-testid":"publish-genre-select",onChange:se=>{le(se.target.value),se.target.value&&qn({genre:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${re?"border-border":"border-amber-500"}`,children:[!re&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),sl.map(se=>d.jsx("option",{value:se,children:se},se))]}),d.jsxs("select",{value:V,"data-testid":"publish-language-select",onChange:se=>{he(se.target.value),se.target.value&&qn({language:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${V?"border-border":"border-amber-500"}`,children:[!V&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(se=>d.jsx("option",{value:se,children:se},se))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ls.count>0){const ye=`This plot contains ${ls.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(ye))return}const se=fi?Dt:null;se?await(s==null?void 0:s(e,t,re,V,_e,se))&&(oe.current=!0,an(null),ln(null),Ot("unknown"),Qe(null),H(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),pt.current&&(pt.current.value="")):s==null||s(e,t,re,V,_e)},disabled:!!a||cr||Rn||ba||fi&&(!re||!V)||Mi&&Le!=="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"}),fi&&c==="cartoon"&&(!re||!V)&&d.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"}),fi&&c!=="cartoon"&&!re&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),fi&&c!=="cartoon"&&re&&!V&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),cr&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Mi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Mi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Mi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",Ce," of ",et," ","still need an uploaded image"]})]}),Mr&&d.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 →"}),ls.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:ls.warnings.map((se,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:se},ye))}),fi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:se=>{Me(se.target.checked),qn({isNsfw:se.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Ip({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Hp({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Ip,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Hp,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Hp,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Ip,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Ip,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Hp,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function du({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(du,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(du,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(du,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(du,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Bu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Bu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Bu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(zf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(zf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(zf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function zf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Bu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Bu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,j]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[q,R]=w.useState(!1),[ie,fe]=w.useState(!1),[be,B]=w.useState(null),[ne,F]=w.useState(!1),[G,Y]=w.useState(null),[U,A]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),B(null),(async()=>{try{const[X,re]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!X.ok){C||(c(!0),a(!1));return}const le=await X.json(),V=re.ok?await re.json().catch(()=>null):null;if(C)return;p(le.title??""),_(le.description??""),b(yu(le.genre)??""),S(le.language&&ts.find(he=>he.toLowerCase()===le.language.toLowerCase())||""),M(!!le.isNsfw),j(le.contentType==="fiction"?"fiction":"cartoon"),te((V==null?void 0:V.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{R(!0),fe(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const X=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(X.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const re=await X.json().catch(()=>({}));B(re.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),ge=w.useCallback(async C=>{var re;const X=(re=C.target.files)==null?void 0:re[0];if(z.current&&(z.current.value=""),!!X){F(!0),B(null);try{let le;try{le=await Gu(X)}catch(Le){B(Le instanceof Error?Le.message:"Could not import image");return}const V=le.type==="image/jpeg"?"jpg":"webp",he=new File([le],`cover.${V}`,{type:le.type}),_e=new FormData;_e.append("file",he);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Me.ok){const Le=await Me.json().catch(()=>({}));B(Le.error||"Cover import failed.");return}te("present"),Y(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),T=w.useCallback(()=>{var X;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.`;(X=navigator.clipboard)==null||X.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",K=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),sl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${K}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:ne,"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:ne?"Importing…":"Import cover"}),d.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:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:ge,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,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"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var Ke,Et;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[j,I]=w.useState(null),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(null),B=async()=>{try{const ze=await t(`/api/stories/${e}/cover-asset`),_t=ze.ok?await ze.json():null;if(!(_t!=null&&_t.found)||!_t.valid||!_t.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(_t.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Vt=await Te.blob();return new File([Vt],String(_t.path).split("/").pop()||"cover.webp",{type:_t.type||Vt.type})}catch{return null}};w.useEffect(()=>{let ze=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),Vt=Te.ok?await Te.json():null;if(ze)return;!Vt||!Array.isArray(Vt.episodes)?(N(!0),x(null)):x(Vt),v(!1)}catch{ze||(N(!0),x(null),v(!1))}})(),()=>{ze=!0}},[e,t,f]);const ne=((Et=(Ke=_==null?void 0:_.episodes)==null?void 0:Ke.find(ze=>!ze.published))==null?void 0:Et.file)??null,F=ne==="genesis.md",G=JSON.stringify([ne??"",f]),[Y,U]=w.useState(null);if(Y!==G&&(U(G),I(null),q(null),ie(null),be(null)),w.useEffect(()=>{if(!ne)return;let ze=!1;const _t=ne.replace(/\.md$/,"");return(async()=>{var Te;try{const Vt=[t(`/api/stories/${e}/${ne}`),t(`/api/stories/${e}/cuts/${_t}`)];F&&Vt.push(t(`/api/stories/${e}/structure.md`));const[ki,Ct,tt]=await Promise.all(Vt);if(ze)return;if(I(ki.ok?(await ki.json()).content??"":""),Ct.ok){const Q=await Ct.json();if(ze)return;q(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else q(null),ie(null);be(F&&tt&&tt.ok?((Te=await tt.json())==null?void 0:Te.content)??null:null)}catch{ze||(I(""),q(null),ie(null),be(null))}})(),()=>{ze=!0}},[ne,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(ze=>!ze.published);if(!A)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=A.cuts,$=_.cover==="present",ge=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",D=A.state==="blocked",K=A.file==="genesis.md",C=!K||!!c&&!!h,X=!!o&&o===A.file,re=j!==null,le=re?Em({fileName:A.file,fileContent:j??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:R}):null,V=!!le&&zo(le,A.file),he=!K&&re&&!km({fileContent:j??"",episodeTitle:R}),_e=V||he,Me=K&&re?Sm(j??""):null,Le=!!Me&&Me.blockers.length>0,He=!K&&re&&te!==null?XS(j??"",te):null,Ce=He&&He.stage==="error"?He.issues:[],et=T&&C&&(re&&(K||te!==null))&&!_e&&!Le&&!X&&!!a,at=async()=>{if(!(!et||!a)){E(null);try{const ze=K?await B():null;await a(e,A.file,c??"",h??"",!!p,ze)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",A.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:ge.map((ze,_t)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":ze.status,children:[d.jsx("span",{className:`flex-shrink-0 ${ze.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:ze.status==="done"?"✓":"○"}),d.jsx("span",{className:ze.status==="done"?"text-foreground":"text-muted",children:ze.label}),ze.detail&&d.jsxs("span",{className:"text-muted",children:["· ",ze.detail]})]},_t))}),le&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":V?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[K?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:le})]}),V?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",K?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",le,"” 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]}),Me&&d.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":Le?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),Me.blockers.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ze},`b-${_t}`)),Me.warnings.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ze},`w-${_t}`))]}),Ce.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(Ce).map(ze=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${ze.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:ze.title})},ze.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:Ce.map((ze,_t)=>d.jsx("li",{className:"font-mono break-words",children:ze},_t))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.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)"}),K&&!C&&d.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&&d.jsxs("button",{onClick:()=>i(e,A.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 ",A.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!et,"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:et?void 0:"Finish the remaining steps above first",children:X?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:A.file})]}),d.jsxs("p",{children:["State: ",A.state," — ",A.summary]}),d.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 qM(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 WM(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?zo(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=qM(i,s);return a?zo(a,t)||Pp(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,Pf=224,If=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[j,I]=w.useState(VM),[te,q]=w.useState([]),[R,ie]=w.useState(!1),[fe,be]=w.useState(""),[B,ne]=w.useState(""),[F,G]=w.useState(""),[Y,U]=w.useState("English"),[A,z]=w.useState("normal"),[$,ge]=w.useState("claude"),[T,D]=w.useState(null),[K,C]=w.useState(!1),[X,re]=w.useState({}),[le,V]=w.useState({}),[he,_e]=w.useState(new Set),[Me,Le]=w.useState(new Set),[He,Ce]=w.useState({}),[Ue,et]=w.useState({}),[at,Ke]=w.useState({}),[Et,ze]=w.useState({}),[_t,Te]=w.useState({}),[Vt,ki]=w.useState({}),[Ct,tt]=w.useState(!1),[Q,xe]=w.useState(!0),je=w.useRef(new Map),$e=w.useRef(new Map),nt=w.useRef(new Map),Wt=w.useRef(new Map),hi=w.useRef(new Set),Lt=w.useRef(null),yt=w.useRef(null),Dt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.address&&E(oe.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(oe=>oe.ok?oe.json():null).then(oe=>{oe&&D(oe)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(j))}catch{}},[j]),w.useEffect(()=>{const oe=()=>{if(!yt.current)return;const O=yt.current.getBoundingClientRect().width-Pf-If;I(ce=>jy(ce,O))};return window.addEventListener("resize",oe),oe(),()=>window.removeEventListener("resize",oe)},[]);const Qe=w.useCallback(()=>{be(""),ne(""),G(""),z("normal"),ge("claude"),ie(!0)},[]),di=w.useCallback(async(oe,O,ce,ke)=>{const De=fe.trim();if(!De)return;const Ee=oe==="cartoon"?"codex":ke;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:O,genre:F||void 0,contentType:oe,agentMode:ce,agentProvider:Ee})});if(!Pe.ok)return;const We=await Pe.json();ie(!1),Ce(rt=>({...rt,[We.name]:oe})),et(rt=>({...rt,[We.name]:O})),F&&Ke(rt=>({...rt,[We.name]:F})),V(rt=>({...rt,[We.name]:Ee})),ce==="bypass"&&re(rt=>({...rt,[We.name]:!0})),s(We.name),o(null)}catch{}},[t,fe,B,F]);w.useEffect(()=>{if(te.length===0)return;const oe=setInterval(async()=>{try{const O=await t("/api/stories");if(!O.ok)return;const ce=await O.json(),ke=new Set(ce.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of ke)if(!hi.current.has(De)&&te.length>0){const Ee=te[0],Pe=je.current.get(Ee)||"fiction",We=$e.current.get(Ee)||"English",rt=nt.current.get(Ee)||"normal",Xe=Wt.current.get(Ee)||"claude";let Nt=!1;Lt.current&&(Nt=await Lt.current(Ee,De,{contentType:Pe,language:We,agentMode:rt,agentProvider:Xe}).catch(()=>!1)),Nt&&(q(jt=>jt.slice(1)),je.current.delete(Ee),$e.current.delete(Ee),nt.current.delete(Ee),Wt.current.delete(Ee),rt==="bypass"&&re(jt=>{const Gt={...jt,[De]:!0};return delete Gt[Ee],Gt}),V(jt=>{const Gt={...jt,[De]:Xe};return delete Gt[Ee],Gt}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:We,agentMode:rt,agentProvider:Xe})}).catch(()=>{})),s(De),o(null)}hi.current=ke}catch{}},3e3);return()=>clearInterval(oe)},[t,te]),w.useEffect(()=>{t("/api/stories").then(oe=>{if(oe.ok)return oe.json()}).then(oe=>{oe!=null&&oe.stories&&(hi.current=new Set(oe.stories.filter(O=>O.name!=="_example").map(O=>O.name)))}).catch(()=>{})},[t]);const H=w.useCallback((oe,O)=>{s(oe),o(O),h(null)},[]),Se=w.useRef(null),Oe=w.useCallback(async oe=>{var O,ce,ke,De;Se.current=oe,s(oe),o(null),h(null);try{const Ee=await t(`/api/stories/${oe}`);if(Ee.ok&&Se.current===oe){const Pe=await Ee.json();if(Pe.contentType==="cartoon")return;const We=Pe.files||[],Xe=((O=We.map(Nt=>{var jt;return{file:Nt.file,num:(jt=Nt.file.match(/^plot-(\d+)\.md$/))==null?void 0:jt[1]}}).filter(Nt=>Nt.num!=null).sort((Nt,jt)=>parseInt(jt.num)-parseInt(Nt.num))[0])==null?void 0:O.file)??((ce=We.find(Nt=>Nt.file==="genesis.md"))==null?void 0:ce.file)??((ke=We.find(Nt=>Nt.file==="structure.md"))==null?void 0:ke.file)??((De=We[0])==null?void 0:De.file);Xe&&Se.current===oe&&o(Xe)}}catch{}},[t]),Ae=w.useCallback(oe=>{oe.preventDefault(),Dt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const O=ke=>{if(!Dt.current||!yt.current)return;const De=yt.current.getBoundingClientRect(),Ee=De.width-Pf-If,Pe=ke.clientX-De.left-Pf;I(jy(Pe/Ee,Ee))},ce=()=>{Dt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",ce)};window.addEventListener("mousemove",O),window.addEventListener("mouseup",ce)},[]),Ge=w.useCallback(async(oe,O,ce,ke,De,Ee)=>{var Xe;f(O),v("Reading file..."),N(null);let Pe=!1,We=null,rt=!1;try{const Nt=await t(`/api/stories/${oe}/${O}`);if(!Nt.ok)throw new Error("Failed to read file");const jt=await Nt.json(),Gt=He[oe];let Mt=null,Ni=null;if(O==="genesis.md")try{const ei=await t(`/api/stories/${oe}/structure.md`);ei.ok&&(Mt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${oe}/cuts/${O.replace(/\.md$/,"")}`);ei.ok&&(Ni=(await ei.json()).title??null)}catch{}const gr=Em({fileName:O,fileContent:jt.content,storySlug:oe,structureContent:Mt,contentType:Gt,episodeTitle:Ni});if(Gt==="cartoon"&&zo(gr,O))return v(O==="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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/)&&!km({fileContent:jt.content,episodeTitle:Ni}))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(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O==="genesis.md"){const ei=Sm(jt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(O.match(/^plot-\d+\.md$/)){if(pM(jt)){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(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${oe}`);if(ei.ok){const Tn=(await ei.json()).files.find(or=>or.file==="genesis.md"&&or.storylineId);Jt=Tn==null?void 0:Tn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Dr=await ei.json();if(gM(Dr))return N(xM(Dr)),f(null),v(""),!1}}catch{}v("Publishing...");const Wi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:oe,fileName:O,title:gr,content:jt.content,genre:ce,language:ke,isNsfw:De,storylineId:Jt,...wy(He,oe,Jt)?{contentType:wy(He,oe,Jt)}:{}})});if(!Wi.ok){const ei=await Wi.json();throw new Error(ei.error||"Publish failed")}const qn=(Xe=Wi.body)==null?void 0:Xe.getReader(),xr=new TextDecoder;if(qn)for(;;){const{done:ei,value:Dr}=await qn.read();if(ei)break;const or=xr.decode(Dr).split(` -`).filter(on=>on.startsWith("data: "));for(const on of or)try{const St=JSON.parse(on.slice(6));if(St.step&&v(St.message||St.step),St.step==="done"&&St.txHash){if(rt=!0,await t(`/api/stories/${oe}/${O}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:St.txHash,storylineId:St.storylineId,plotIndex:St.plotIndex,contentCid:St.contentCid,gasCost:St.gasCost,indexError:St.indexError,authorAddress:M})}),x(An=>An+1),Ee&&O==="genesis.md"&&St.storylineId){v("Uploading cover...");let An=null;try{An=await uM(t,St.storylineId,Ee)}catch{}An||(Pe=!0)}if(Gt==="cartoon"&&St.storylineId)try{const An=O!=="genesis.md",Go=`storylineId=${St.storylineId}`+(An&&St.plotIndex!=null?`&plotIndex=${St.plotIndex}`:""),_r=await t(`/api/publish/public-title?${Go}`);if(_r.ok){const fi=await _r.json(),xn=An?{plots:fi.plotTitle!=null?[{plotIndex:St.plotIndex,title:fi.plotTitle}]:[]}:{title:fi.storylineTitle},Mi=WM({fileName:O,detail:xn,plotIndex:St.plotIndex});Mi.ok||(We=GM(Mi))}}catch{}}}catch{}}We&&N(We),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Nt){const jt=Nt instanceof Error?Nt.message:"Publish failed";v(`Error: ${jt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return rt&&!Pe},[t,He,M]),Fe=w.useCallback(oe=>{oe.startsWith("_new_")&&(q(O=>O.filter(ce=>ce!==oe)),je.current.delete(oe),$e.current.delete(oe),nt.current.delete(oe),Wt.current.delete(oe),re(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}),V(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}))},[]);w.useEffect(()=>{const oe=ce=>{_e(new Set(ce.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Le(new Set(ce.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const ke={},De={},Ee={},Pe={},We={},rt={};for(const Xe of ce)ke[Xe.name]=Xe.contentType||"fiction",De[Xe.name]=Xe.language,Ee[Xe.name]=Xe.genre,Pe[Xe.name]=Xe.isNsfw,We[Xe.name]=Xe.agentProvider,Xe.title&&(rt[Xe.name]=Xe.title);Ce(ke),et(De),Ke(Ee),ze(Pe),ki(We),Te(rt)};t("/api/stories").then(ce=>ce.ok?ce.json():null).then(ce=>{ce!=null&&ce.stories&&oe(ce.stories)}).catch(()=>{});const O=setInterval(async()=>{try{const ce=await t("/api/stories");if(ce.ok){const ke=await ce.json();oe(ke.stories)}}catch{}},5e3);return()=>clearInterval(O)},[t]);const dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",ft=!!T&&!dt,ct=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Kt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const oe=i;if((await t(`/api/stories/${oe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ki(ce=>({...ce,[oe]:"codex"})),V(ce=>({...ce,[oe]:"codex"}));try{const ce=await t("/api/stories");if(ce.ok){const ke=await ce.json();if(ke!=null&&ke.stories){const De={};for(const Ee of ke.stories)De[Ee.name]=Ee.agentProvider;ki(De)}}}catch{}}},[t,i]),Ei=w.useCallback(oe=>{i===oe&&(s(null),o(null))},[i]),pt=i?le[i]??Vt[i]:void 0,qi=Lf(i,He,je.current),jn=mM(qi,pt,i),sn=!!i&&qi==="cartoon",Fn=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",an=w.useCallback(oe=>{const O=i;if(O)switch(oe){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":H(O,"structure.md");break;case"genesis":H(O,"genesis.md");break;case"publish":h("publish");break}},[i,H]),gn=w.useCallback((oe,O)=>{const ce=i;if(ce)switch(oe){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":O&&H(ce,O);break}},[i,H]),ln=w.useCallback(oe=>{i&&(oe.genre!==void 0&&Ke(O=>({...O,[i]:oe.genre||void 0})),oe.language!==void 0&&et(O=>({...O,[i]:oe.language||void 0})),oe.isNsfw!==void 0&&ze(O=>({...O,[i]:oe.isNsfw})))},[i]),mr=w.useCallback(oe=>{tt(oe),xe(!oe)},[]),Ot=Ct&&!Q;return d.jsxs("div",{ref:yt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Ot?"stories-focused-lettering-mode":"stories-default-layout",children:[!Ot&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:H,onNewStory:Qe,untitledSessions:te})}),!Ot&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${j} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Oe,onDestroySession:Fe,onArchiveStory:Ei,confirmedStories:he,renameRef:Lt,bypassStories:X,agentProviders:le,readiness:T,contentType:Lf(i,He,je.current),needsProviderRepair:jn,onRepairProvider:Kt})}),!Ot&&d.jsx("div",{onMouseDown:Ae,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:If,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Ot?{flex:"1 0 0"}:{flex:`${1-j} 0 0`},children:[!Ct&&sn&&i&&d.jsx(HM,{storyTitle:_t[i]||i,active:Fn,onSelect:an}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:sn&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:ln}):sn&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:H}):sn&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:at[i],language:Ue[i],isNsfw:Et[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:H}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:M,contentType:Lf(i,He,je.current)||"fiction",language:i?Ue[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?Et[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:oe=>i&&H(i,oe),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:mr,onFocusedLetteringWorkspaceVisibleChange:xe})}),!Ct&&sn&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:gn,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:oe=>be(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:oe=>ne(oe.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:oe=>G(oe.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:[d.jsx("option",{value:"",children:"— Select later —"}),sl.map(oe=>d.jsx("option",{value:oe,children:oe},oe))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:Y,onChange:oe=>U(oe.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:ts.map(oe=>d.jsx("option",{value:oe,children:oe},oe))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:A,onChange:oe=>z(oe.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:oe=>ge(oe.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>di("fiction",Y,A,$),disabled:!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>di("cartoon",Y,A,"codex"),disabled:ft||!fe.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),wu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:$p}),T&&T.codex.installed&&!wu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:ct,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:K?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{Op as M,ko as a,$S as b,$D as c,$3 as d,Co as l,vm as s,YS as t,n4 as v}; diff --git a/app/web/dist/assets/index-OmkX9BzW.js b/app/web/dist/assets/index-OmkX9BzW.js new file mode 100644 index 0000000..350202f --- /dev/null +++ b/app/web/dist/assets/index-OmkX9BzW.js @@ -0,0 +1,141 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Pu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vd={exports:{}},oo={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ib;function pC(){if(ib)return oo;ib=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 oo.Fragment=t,oo.jsx=i,oo.jsxs=i,oo}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={exports:{}},Qe={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var rb;function gC(){if(rb)return Qe;rb=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"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,M={};function E(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,X){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,X,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function O(){}O.prototype=E.prototype;function H(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}var A=H.prototype=new O;A.constructor=H,N(A,E.prototype),A.isPureReactComponent=!0;var W=Array.isArray;function R(){}var re={H:null,A:null,T:null,S:null},he=Object.prototype.hasOwnProperty;function be(D,X,C){var Z=C.ref;return{$$typeof:e,type:D,key:X,ref:Z!==void 0?Z:null,props:C}}function B(D,X){return be(D.type,X,D.props)}function se(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function F(D){var X={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(C){return X[C]})}var Y=/\/+/g;function V(D,X){return typeof D=="object"&&D!==null&&D.key!=null?F(""+D.key):X.toString(36)}function U(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(R,R):(D.status="pending",D.then(function(X){D.status==="pending"&&(D.status="fulfilled",D.value=X)},function(X){D.status==="pending"&&(D.status="rejected",D.reason=X)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function T(D,X,C,Z,ae){var oe=typeof D;(oe==="undefined"||oe==="boolean")&&(D=null);var K=!1;if(D===null)K=!0;else switch(oe){case"bigint":case"string":case"number":K=!0;break;case"object":switch(D.$$typeof){case e:case t:K=!0;break;case _:return K=D._init,T(K(D._payload),X,C,Z,ae)}}if(K)return ae=ae(D),K=Z===""?"."+V(D,0):Z,W(ae)?(C="",K!=null&&(C=K.replace(Y,"$&/")+"/"),T(ae,X,C,"",function(Me){return Me})):ae!=null&&(se(ae)&&(ae=B(ae,C+(ae.key==null||D&&D.key===ae.key?"":(""+ae.key).replace(Y,"$&/")+"/")+K)),X.push(ae)),1;K=0;var de=Z===""?".":Z+":";if(W(D))for(var ge=0;ge>>1,j=T[xe];if(0>>1;xea(C,q))Za(ae,C)?(T[xe]=ae,T[Z]=q,xe=Z):(T[xe]=C,T[X]=q,xe=X);else if(Za(ae,q))T[xe]=ae,T[Z]=q,xe=Z;else break e}}return z}function a(T,z){var q=T.sortIndex-z.sortIndex;return q!==0?q:T.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,H=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function W(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(W,z.startTime-T)}}var R=!1,re=-1,he=5,be=-1;function B(){return M?!0:!(e.unstable_now()-beT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&U(W,D.startTime-T),z=!1}}break e}finally{x=null,b=q,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof H=="function")F=function(){H(se)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,V=Y.port2;Y.port1.onmessage=se,F=function(){V.postMessage(null)}}else F=function(){E(se,0)};function U(T,z){re=E(function(){T(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(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=q,t(f,T),i(p)===null&&T===i(f)&&(N?(O(re),re=-1):N=!0,U(W,q-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,F()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var q=b;b=z;try{return T.apply(this,arguments)}finally{b=q}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},sn={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ob;function vC(){if(ob)return sn;ob=1;var e=$p();function t(p){var f="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(),Jd.exports=vC(),Jd.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ub;function SC(){if(ub)return co;ub=1;var e=bC(),t=$p(),i=yC();function s(n){var r="https://react.dev/errors/"+n;if(1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function de(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function Me(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function Pe(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),ro._currentValue=q)}var Fe,Se;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",Se=-1)":-1m||L[u]!==ee[m]){var ue=` +`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{Je=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function et(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return He("Activity");default:return""}}function jt(n){try{var r="",l=null;do r+=et(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +Error generating stack: `+u.message+` +`+u.stack}}var Oe=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,je=e.unstable_cancelCallback,Gt=e.unstable_shouldYield,yi=e.unstable_requestPaint,kt=e.unstable_now,Xe=e.unstable_getCurrentPriorityLevel,te=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Be=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Ke=e.unstable_IdlePriority,Yt=e.log,fi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Ht(n){if(typeof Yt=="function"&&fi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var nt=Math.clz32?Math.clz32:we,Xt=Math.log,$=Math.LN2;function we(n){return n>>>=0,n===0?32:31-(Xt(n)/$|0)|0}var Ee=256,Ae=262144,Ye=4194304;function Ue(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 ut(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(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 vt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(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 Bt(){var n=Ye;return Ye<<=1,(Ye&62914560)===0&&(Ye=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Vt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function rn(n,r,l,u,m,g){var y=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,L=n.expirationTimes,ee=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Sa=/[\n"\\]/g;function Oi(n){return n.replace(Sa,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function mi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ai(r)):n.value!==""+Ai(r)&&(n.value=""+Ai(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Vi(n,y,Ai(r)):l!=null?Vi(n,y,Ai(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=""+Ai(k):n.removeAttribute("name")}function gr(n,r,l,u,m,g,y,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)){Mn(n);return}l=l!=null?""+Ai(l):"",r=r!=null?""+Ai(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Mn(n)}function Vi(n,r,l){r==="number"&&mr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Ki(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"),hs=!1;if(lr)try{var ds={};Object.defineProperty(ds,"passive",{get:function(){hs=!0}}),window.addEventListener("test",ds,ds),window.removeEventListener("test",ds,ds)}catch{hs=!1}var ne=null,ke=null,Ne=null;function it(){if(Ne)return Ne;var n,r=ke,l=r.length,u,m="value"in ne?ne.value:ne.textContent,g=m.length;for(n=0;n=kl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ca=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(Ca)return n==="compositionend"||!eh&&Bm(n,r)?(n=it(),Ne=ke=ne=null,Ca=!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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=mr(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=mr(n.document)}return r}function nh(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 Y1=lr&&"documentMode"in document&&11>=document.documentMode,ka=null,rh=null,Tl=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||ka==null||ka!==mr(u)||(u=ka,"selectionStart"in u&&nh(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}),Tl&&jl(Tl,u)||(Tl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-nt(r)+m|l<lt?(_t=Ie,Ie=null):_t=Ie.sibling;var Nt=ie(G,Ie,J[lt],fe);if(Nt===null){Ie===null&&(Ie=_t);break}n&&Ie&&Nt.alternate===null&&r(G,Ie),I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt,Ie=_t}if(lt===J.length)return l(G,Ie),bt&&Hr(G,lt),qe;if(Ie===null){for(;ltlt?(_t=Ie,Ie=null):_t=Ie.sibling;var Bs=ie(G,Ie,Nt.value,fe);if(Bs===null){Ie===null&&(Ie=_t);break}n&&Ie&&Bs.alternate===null&&r(G,Ie),I=g(Bs,I,lt),Et===null?qe=Bs:Et.sibling=Bs,Et=Bs,Ie=_t}if(Nt.done)return l(G,Ie),bt&&Hr(G,lt),qe;if(Ie===null){for(;!Nt.done;lt++,Nt=J.next())Nt=pe(G,Nt.value,fe),Nt!==null&&(I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt);return bt&&Hr(G,lt),qe}for(Ie=u(Ie);!Nt.done;lt++,Nt=J.next())Nt=le(Ie,G,lt,Nt.value,fe),Nt!==null&&(n&&Nt.alternate!==null&&Ie.delete(Nt.key===null?lt:Nt.key),I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt);return n&&Ie.forEach(function(fC){return r(G,fC)}),bt&&Hr(G,lt),qe}function Pt(G,I,J,fe){if(typeof J=="object"&&J!==null&&J.type===N&&J.key===null&&(J=J.props.children),typeof J=="object"&&J!==null){switch(J.$$typeof){case v:e:{for(var qe=J.key;I!==null;){if(I.key===qe){if(qe=J.type,qe===N){if(I.tag===7){l(G,I.sibling),fe=m(I,J.props.children),fe.return=G,G=fe;break e}}else if(I.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===he&&ia(qe)===I.type){l(G,I.sibling),fe=m(I,J.props),Ll(fe,J),fe.return=G,G=fe;break e}l(G,I);break}else r(G,I);I=I.sibling}J.type===N?(fe=Zs(J.props.children,G.mode,fe,J.key),fe.return=G,G=fe):(fe=rc(J.type,J.key,J.props,null,G.mode,fe),Ll(fe,J),fe.return=G,G=fe)}return y(G);case S:e:{for(qe=J.key;I!==null;){if(I.key===qe)if(I.tag===4&&I.stateNode.containerInfo===J.containerInfo&&I.stateNode.implementation===J.implementation){l(G,I.sibling),fe=m(I,J.children||[]),fe.return=G,G=fe;break e}else{l(G,I);break}else r(G,I);I=I.sibling}fe=dh(J,G.mode,fe),fe.return=G,G=fe}return y(G);case he:return J=ia(J),Pt(G,I,J,fe)}if(U(J))return ze(G,I,J,fe);if(F(J)){if(qe=F(J),typeof qe!="function")throw Error(s(150));return J=qe.call(J),Ge(G,I,J,fe)}if(typeof J.then=="function")return Pt(G,I,hc(J),fe);if(J.$$typeof===H)return Pt(G,I,lc(G,J),fe);dc(G,J)}return typeof J=="string"&&J!==""||typeof J=="number"||typeof J=="bigint"?(J=""+J,I!==null&&I.tag===6?(l(G,I.sibling),fe=m(I,J),fe.return=G,G=fe):(l(G,I),fe=hh(J,G.mode,fe),fe.return=G,G=fe),y(G)):l(G,I)}return function(G,I,J,fe){try{Bl=0;var qe=Pt(G,I,J,fe);return Oa=null,qe}catch(Ie){if(Ie===La||Ie===cc)throw Ie;var Et=Ln(29,Ie,null,G.mode);return Et.lanes=fe,Et.return=G,Et}finally{}}}var ra=gg(!0),xg=gg(!1),xs=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 _s(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function bs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ol(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,vn(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function zl(){if(Nh){var n=Ba;if(n!==null)throw n}}function Pl(n,r,l,u){Nh=!1;var m=n.updateQueue;xs=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,ee=L.next;L.next=null,y===null?g=ee:y.next=ee,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=ee:k.next=ee,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=ee=L=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(xt&ie)===ie:(u&ie)===ie){ie!==0&&ie===Ma&&(Nh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var ze=n,Ge=k;ie=r;var Pt=l;switch(Ge.tag){case 1:if(ze=Ge.payload,typeof ze=="function"){pe=ze.call(Pt,pe,ie);break e}pe=ze;break e;case 3:ze.flags=ze.flags&-65537|128;case 0:if(ze=Ge.payload,ie=typeof ze=="function"?ze.call(Pt,pe,ie):ze,ie==null)break e;pe=x({},pe,ie);break e;case 2:xs=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(ee=ue=le,L=pe):ue=ue.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=ee,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Cs|=y,n.lanes=y,n.memoizedState=pe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var L=m(),ee=T.S;if(ee!==null&&ee(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=iw(L,u);Ul(n,r,ue,Hn(n))}else Ul(n,r,u,Hn(n))}catch(pe){Ul(n,r,{then:function(){},status:"rejected",reason:pe},Hn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,q,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:q,baseState:q,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qr,lastRenderedState:q},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Ul(n,r.next.queue,{},Hn())}function Wh(){return Zi(ro)}function Jg(){return bi().memoizedState}function ex(){return bi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Hn();n=_s(l);var u=bs(r,n,l);u!==null&&(Nn(u,r,l),Ol(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Hn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(Nn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Hn();Ul(n,r,l,u)}function Ul(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Bn(k,y))return ic(n,r,m,0),qt===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return Nn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&Nn(r,n,2)}function Sc(n){var r=n.alternate;return n===st||r!==null&&r===st}function ix(n,r){Pa=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,vn(n,l)}}var $l={readContext:Zi,use:_c,useCallback:oi,useContext:oi,useEffect:oi,useImperativeHandle:oi,useLayoutEffect:oi,useInsertionEffect:oi,useMemo:oi,useReducer:oi,useRef:oi,useState:oi,useDebugValue:oi,useDeferredValue:oi,useTransition:oi,useSyncExternalStore:oi,useId:oi,useHostTransitionStatus:oi,useFormState:oi,useActionState:oi,useOptimistic:oi,useMemoCache:oi,useCacheRefresh:oi};$l.useEffectEvent=oi;var rx={readContext:Zi,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Zi,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Ht(!0);try{n()}finally{Ht(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Ht(!0);try{l(r)}finally{Ht(!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=uw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,st,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),qt===null)throw Error(s(349));(xt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Ha(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=qt.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-nt(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Zt]=r,g[Q]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Ji(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&&Gr(r)}}return Jt(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Gr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ra(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Xi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Zt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||ms(r,!0)}else n=$c(n).createTextNode(u),n[Zt]=r,r.stateNode=n}return Jt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ra(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Jt(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(zn(r),r):(zn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Jt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ra(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Jt(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(zn(r),r):(zn(r),null)}return zn(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),Nc(r,r.updateQueue),Jt(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),Jt(r),null;case 10:return $r(r.type),Jt(r),null;case 19:if(X(_i),u=r.memoizedState,u===null)return Jt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)ql(u,!1);else{if(ci!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,ql(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(_i,_i.current&1|2),bt&&Hr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&kt()>Dc&&(r.flags|=128,m=!0,ql(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),ql(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return Jt(r),null}else 2*kt()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,ql(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=kt(),n.sibling=null,l=_i.current,C(_i,m?l&1|2:l&1),bt&&Hr(r,u.treeForkCount),n):(Jt(r),null);case 22:case 23:return zn(r),Th(),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&&(Jt(r),r.subtreeFlags&6&&(r.flags|=8192)):Jt(r),l=r.updateQueue,l!==null&&Nc(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&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),$r(wi),Jt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return $r(wi),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Pe(r),null;case 31:if(r.memoizedState!==null){if(zn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(zn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(_i),null;case 4:return ge(),null;case 10:return $r(r.type),null;case 22:case 23:return zn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return $r(wi),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:$r(wi),ge();break;case 26:case 27:case 5:Pe(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&zn(r);break;case 13:zn(r);break;case 19:X(_i);break;case 10:$r(r.type);break;case 22:case 23:zn(r),Th(),n!==null&&X(ta);break;case 24:$r(wi)}}function Wl(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function Ss(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,ee=k;try{ee()}catch(ue){Mt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){Mt(r,r.return,ue)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Gl(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){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(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){Mt(n,r,m)}else l.current=null}function Rx(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){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[Q]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ts(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&Ts(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 cd(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=Gn));else if(u!==4&&(u===27&&Ts(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&Ts(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Ji(r,u,l),r[Zt]=n,r[Q]=l}catch(g){Mt(n,n.return,g)}}var Yr=!1,Ei=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,zi=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(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 y=0,k=-1,L=-1,ee=0,ue=0,pe=n,ie=null;t:for(;;){for(var le;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(le=pe.firstChild)!==null;)ie=pe,pe=le;for(;;){if(pe===n)break t;if(ie===l&&++ee===m&&(k=y),ie===g&&++ue===u&&(L=y),(le=pe.nextSibling)!==null)break;pe=ie,ie=pe.parentNode}pe=le}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,zi=r;zi!==null;)if(r=zi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,zi=n;else for(;zi!==null;){switch(r=zi,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"))),Ji(g,u,l),g[Zt]=n,Ze(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ge,Ge=y);var G=qm(k,Ge),I=qm(k,Pt);if(G&&I&&(le.rangeCount!==1||le.anchorNode!==G.node||le.anchorOffset!==G.offset||le.focusNode!==I.node||le.focusOffset!==I.offset)){var J=pe.createRange();J.setStart(G.node,G.offset),le.removeAllRanges(),Ge>Pt?(le.addRange(J),le.extend(I.node,I.offset)):(J.setEnd(I.node,I.offset),le.addRange(J))}}}}for(pe=[],le=k;le=le.parentNode;)le.nodeType===1&&pe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=Es,y=Qr;if(Ri=0,Wa=Es=null,Qr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Ql(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Vn(l,r),r=Xh(n.stateNode,r,2),n=bs(n,r,2),n!==null&&(Vt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ks===null||!ks.has(u))){n=Vn(l,n),l=dx(2),u=bs(r,l,2),u!==null&&(fx(l,u,r,n),Vt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,qt===n&&(xt&l)===l&&(ci===4||ci===3&&(xt&62914560)===xt&&300>kt()-Rc?(Tt&2)===0&&Ga(n,0):pd|=l,qa===xt&&(qa=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Vt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Va=null,Sd=!1,Ic=!1,wd=!1,js=0;function Cr(n){n!==Va&&n.next===null&&(Va===null?Pc=Va=n:Va=Va.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Ql(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-nt(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=xt,g=ut(u,u===qt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||vt(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;js!==0&&Iw()&&(n=js);for(var r=kt(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Va=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Ri!==0&&Ri!==5||Ql(n),js!==0&&(js=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&C_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function O_(n,r,l){var u=Ka;if(u&&typeof r=="string"&&r){var m=Oi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Ji(r,"link",n),Ze(r),u.head.appendChild(r)))}}function Vw(n){Jr.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){Jr.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){Jr.L(n,r,l);var u=Ka;if(u&&n&&r){var m='link[rel="preload"][as="'+Oi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Oi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Oi(l.imageSizes)+'"]')):m+='[href="'+Oi(n)+'"]';var g=m;switch(r){case"style":g=Xa(n);break;case"script":g=Za(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(io(g))||r==="script"&&u.querySelector(no(g))||(r=u.createElement("link"),Ji(r,"link",n),Ze(r),u.head.appendChild(r)))}}function Zw(n,r){Jr.m(n,r);var l=Ka;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Oi(u)+'"][href="'+Oi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Za(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(no(g)))return}u=l.createElement("link"),Ji(u,"link",n),Ze(u),l.head.appendChild(u)}}}function Qw(n,r,l){Jr.S(n,r,l);var u=Ka;if(u&&n){var m=Ct(u).hoistableStyles,g=Xa(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(io(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Id(n,l);var L=y=u.createElement("link");Ze(L),Ji(L,"link",n),L._p=new Promise(function(ee,ue){L.onload=ee,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){Jr.X(n,r);var l=Ka;if(l&&n){var u=Ct(l).hoistableScripts,m=Za(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Ze(g),Ji(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){Jr.M(n,r);var l=Ka;if(l&&n){var u=Ct(l).hoistableScripts,m=Za(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Ze(g),Ji(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(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=Xa(l.href),l=Ct(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=Xa(l.href);var g=Ct(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(io(n)))&&!g._p&&(y.instance=g,y.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||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Za(l),l=Ct(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 Xa(n){return'href="'+Oi(n)+'"'}function io(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),Ji(r,"link",l),Ze(r),n.head.appendChild(r))}function Za(n){return'[src="'+Oi(n)+'"]'}function no(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Oi(l.href)+'"]');if(u)return r.instance=u,Ze(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"),Ze(u),Ji(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Xa(l.href);var g=n.querySelector(io(m));if(g)return r.state.loading|=4,r.instance=g,Ze(g),g;u=P_(l),(m=er.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Ze(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ji(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Za(l.src),(m=n.querySelector(no(g)))?(r.instance=m,Ze(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Ze(m),Ji(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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=Xa(u.href),g=r.querySelector(io(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Ze(g);return}g=r.ownerDocument||r,u=P_(u),(m=er.get(m))&&Id(u,m),g=g.createElement("link"),Ze(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ji(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,O)=>fetch(E,{...O,headers:{...O==null?void 0:O.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),O=await E.json();if(!E.ok)throw new Error(O.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const O=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),H=await O.json();if(!O.ok)throw new Error(H.error||"Wallet switch failed");b()}catch(O){_(O instanceof Error?O.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[O,H]=w.useState(""),[A,W]=w.useState(!1),[R,re]=w.useState(null),[he,be]=w.useState(""),[B,se]=w.useState(null),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,z]=w.useState(null),[q,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){re("Agent name is required");return}if(!M.trim()){re("Description is required");return}W(!0),re(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...O.trim()&&{genre:O}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){re(ae instanceof Error?ae.message:"Registration failed")}W(!1)},X=async()=>{if(!he.trim()||!/^0x[a-fA-F0-9]{40}$/.test(he)){U("Enter a valid wallet address (0x...)");return}Y(!0),U(null),se(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:he})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");se(oe)}catch(ae){U(ae instanceof Error?ae.message:"Failed to generate binding code")}Y(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!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 ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:O,onChange:ae=>H(ae.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.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:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(q==null?void 0:q.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(q==null?void 0:q.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:q!=null&&q.codex.installed?q.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(q)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.checkedAt?new Date(q.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:he,onChange:ae=>be(ae.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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:F||!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:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.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"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const W=await e("/api/stories");if(W.ok){const R=await W.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const W=await e("/api/stories/archived");if(W.ok){const R=await W.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async W=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:W})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const W=setInterval(S,5e3);return()=>clearInterval(W)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(W=>new Set(W).add(t))},[t]);const E=W=>{x(R=>{const re=new Set(R);return re.has(W)?re.delete(W):re.add(W),re})},O=W=>{var re;const R=W.map(he=>{var be;return{file:he.file,num:(be=he.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(he=>he.num!=null).sort((he,be)=>parseInt(be.num)-parseInt(he.num));return R.length>0?R[0].file:W.some(he=>he.file==="genesis.md")?"genesis.md":W.some(he=>he.file==="structure.md")?"structure.md":((re=W[0])==null?void 0:re.file)??null},H=W=>{if(E(W.name),W.contentType==="cartoon")s(W.name,"");else{const R=O(W.files);R&&s(W.name,R)}},A=W=>{const R=re=>{if(re==="structure.md")return 0;if(re==="genesis.md")return 1;const he=re.match(/^plot-(\d+)\.md$/);return he?2+parseInt(he[1]):100};return[...W].sort((re,he)=>R(re.file)-R(he.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(W=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:W.name,children:W.title||W.name}),d.jsx("button",{onClick:()=>M(W.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},W.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(W=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(W,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===W?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},W)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(W=>W.name!=="_example").map(W=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>H(W),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(W.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:W.name,children:W.title||W.name}),W.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[W.publishedCount,"/",W.files.length]})]}),_.has(W.name)&&d.jsx("div",{className:"pl-4",children:A(W.files).map(R=>{const re=t===W.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(W.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${re?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},W.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},di=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Is(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",Us=" ",Uo=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 zy;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}},Nu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Iy extends Uo{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Is(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()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Gi(e){if(tf.has(e))return tf.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");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Gi("BufferService"),Hy=Gi("CoreMouseService"),va=Gi("CoreService"),qC=Gi("CharsetService"),qp=Gi("InstantiationService"),Uy=Gi("LogService"),bn=Gi("OptionsService"),$y=Gi("OscLinkService"),WC=Gi("UnicodeService"),$o=Gi("DecorationService"),qf=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,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=di([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(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 Hu=Gi("CharSizeService"),ss=Gi("CoreBrowserService"),Wp=Gi("MouseService"),as=Gi("RenderService"),YC=Gi("SelectionService"),Fy=Gi("CharacterJoinerService"),pl=Gi("ThemeService"),qy=Gi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function Un(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let W=A.length-1;W>=0;W--)yield A[W]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,W){let R=0;for(let re of A)if(W(re,R++))return!0;return!1}e.some=_;function x(A,W){for(let R of A)if(W(R))return R}e.find=x;function*b(A,W){for(let R of A)W(R)&&(yield R)}e.filter=b;function*v(A,W){let R=0;for(let re of A)yield W(re,R++)}e.map=v;function*S(A,W){let R=0;for(let re of A)yield*W(re,R++)}e.flatMap=S;function*N(...A){for(let W of A)yield*W}e.concat=N;function M(A,W,R){let re=R;for(let he of A)re=W(re,he);return re}e.reduce=M;function*E(A,W,R=A.length){for(W<0&&(W+=A.length),R<0?R+=A.length:R>A.length&&(R=A.length);W1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function tk(...e){return ni(()=>xa(e))}function ni(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{xa(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var $s=Yy,dt=class{constructor(){this._store=new $s,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 hl=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}},rs=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var ai=Vf,xb=class{constructor(){this._first=ai.Undefined,this._last=ai.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ai.Undefined}clear(){let e=this._first;for(;e!==ai.Undefined;){let t=e.next;e.prev=ai.Undefined,e.next=ai.Undefined,e=t}this._first=ai.Undefined,this._last=ai.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ai(e);if(this._first===ai.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!==ai.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ai.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ai.Undefined&&e.next!==ai.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ai.Undefined&&e.next===ai.Undefined?(this._first=ai.Undefined,this._last=ai.Undefined):e.next===ai.Undefined?(this._last=this._last.prev,this._last.next=ai.Undefined):e.prev===ai.Undefined&&(this._first=this._first.next,this._first.prev=ai.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ai.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},nn;(e=>{e.None=()=>dt.None;function t(F,Y){return x(F,()=>{},0,void 0,!0,void 0,Y)}e.defer=t;function i(F){return(Y,V=null,U)=>{let T=!1,z;return z=F(q=>{if(!T)return z?z.dispose():T=!0,Y.call(V,q)},null,U),T&&z.dispose(),z}}e.once=i;function s(F,Y,V){return f((U,T=null,z)=>F(q=>U.call(T,Y(q)),null,z),V)}e.map=s;function a(F,Y,V){return f((U,T=null,z)=>F(q=>{Y(q),U.call(T,q)},null,z),V)}e.forEach=a;function o(F,Y,V){return f((U,T=null,z)=>F(q=>Y(q)&&U.call(T,q),null,z),V)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(Y,V=null,U)=>{let T=tk(...F.map(z=>z(q=>Y.call(V,q))));return _(T,U)}}e.any=h;function p(F,Y,V,U){let T=V;return s(F,z=>(T=Y(T,z),T),U)}e.reduce=p;function f(F,Y){let V,U={onWillAddFirstListener(){V=F(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new Ce(U);return Y==null||Y.add(T),T.event}function _(F,Y){return Y instanceof Array?Y.push(F):Y&&Y.add(F),F}function x(F,Y,V=100,U=!1,T=!1,z,q){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=F(oe=>{X++,j=Y(j,oe),U&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!U||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new Ce(Z);return q==null||q.add(ae),ae.event}e.debounce=x;function b(F,Y=0,V){return e.debounce(F,(U,T)=>U?(U.push(T),U):[T],Y,void 0,!0,void 0,V)}e.accumulate=b;function v(F,Y=(U,T)=>U===T,V){let U=!0,T;return o(F,z=>{let q=U||!Y(z,T);return U=!1,T=z,q},V)}e.latch=v;function S(F,Y,V){return[e.filter(F,Y,V),e.filter(F,U=>!Y(U),V)]}e.split=S;function N(F,Y=!1,V=[],U){let T=V.slice(),z=F(j=>{T?T.push(j):xe.fire(j)});U&&U.add(z);let q=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new Ce({onWillAddFirstListener(){z||(z=F(j=>xe.fire(j)),U&&U.add(z))},onDidAddFirstListener(){T&&(Y?setTimeout(q):q())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(xe),xe.event}e.buffer=N;function M(F,Y){return(V,U,T)=>{let z=Y(new O);return F(function(q){let xe=z.evaluate(q);xe!==E&&V.call(U,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(Y){return this.steps.push(Y),this}forEach(Y){return this.steps.push(V=>(Y(V),V)),this}filter(Y){return this.steps.push(V=>Y(V)?V:E),this}reduce(Y,V){let U=V;return this.steps.push(T=>(U=Y(U,T),U)),this}latch(Y=(V,U)=>V===U){let V=!0,U;return this.steps.push(T=>{let z=V||!Y(T,U);return V=!1,U=T,z?T:E}),this}evaluate(Y){for(let V of this.steps)if(Y=V(Y),Y===E)break;return Y}}function H(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.on(Y,U),z=()=>F.removeListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:z});return q.event}e.fromNodeEventEmitter=H;function A(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.addEventListener(Y,U),z=()=>F.removeEventListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:z});return q.event}e.fromDOMEventEmitter=A;function W(F){return new Promise(Y=>i(F)(Y))}e.toPromise=W;function R(F){let Y=new Ce;return F.then(V=>{Y.fire(V)},()=>{Y.fire(void 0)}).finally(()=>{Y.dispose()}),Y.event}e.fromPromise=R;function re(F,Y){return F(V=>Y.fire(V))}e.forward=re;function he(F,Y,V){return Y(V),F(U=>Y(U))}e.runAndSubscribe=he;class be{constructor(Y,V){this._observable=Y,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{Y.addObserver(this)},onDidRemoveLastListener:()=>{Y.removeObserver(this)}};this.emitter=new Ce(U),V&&V.add(this.emitter)}beginUpdate(Y){this._counter++}handlePossibleChange(Y){}handleChange(Y,V){this._hasChanged=!0}endUpdate(Y){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function B(F,Y){return new be(F,Y).emitter.event}e.fromObservable=B;function se(F){return(Y,V,U)=>{let T=0,z=!1,q={beginUpdate(){T++},endUpdate(){T--,T===0&&(F.reportChanges(),z&&(z=!1,Y.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver(q),F.reportChanges();let xe={dispose(){F.removeObserver(q)}};return U instanceof $s?U.add(xe):Array.isArray(U)&&U.push(xe),xe}}e.fromObservableLight=se})(nn||(nn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),dt.None}if(this._disposed)return dt.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ni(()=>{o==null||o(),this._removeListener(a)});return s instanceof $s?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Ce,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Ce,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}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var ml=typeof navigator=="object"?navigator.userAgent:"",Jf=ml.indexOf("Firefox")>=0,gk=ml.indexOf("AppleWebKit")>=0,Yp=ml.indexOf("Chrome")>=0,xk=!Yp&&ml.indexOf("Safari")>=0;ml.indexOf("Electron/")>=0;ml.indexOf("Android")>=0;var rf=!1;if(typeof rs.matchMedia=="function"){let e=rs.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=rs.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(rs,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var al="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=al,_b=al,_k,hr,ga=globalThis,tn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?tn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(tn=process);var Ay,bk=typeof((Ay=tn==null?void 0:tn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(tn==null?void 0:tn.type)==="renderer",Ry;if(typeof tn=="object"){ep=tn.platform==="win32",tp=tn.platform==="darwin",xu=tn.platform==="linux",xu&&tn.env.SNAP&&tn.env.SNAP_REVISION,tn.env.CI||tn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=al,_u=al;let e=tn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||al,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(hr=navigator.userAgent,ep=hr.indexOf("Windows")>=0,tp=hr.indexOf("Macintosh")>=0,(hr.indexOf("Macintosh")>=0||hr.indexOf("iPad")>=0||hr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=hr.indexOf("Linux")>=0,(hr==null?void 0:hr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||al,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=hr,Ls=_u,Sk;(e=>{function t(){return Ls}e.value=t;function i(){return Ls.length===2?Ls==="en":Ls.length>=3?Ls[0]==="e"&&Ls[1]==="n"&&Ls[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ls==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.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}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var Ja=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ja&&Ja.clipboard&&Ja.clipboard.writeText,bb||Ja&&Ja.clipboard&&Ja.clipboard.readText;var Vp=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}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:nn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new Ce),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ni(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=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 Ce,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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:rs,disposables:new $s};e.set(rs.vscodeWindowId,t);let i=new Ce,s=new Ce,a=new Ce;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 $s,p={window:c,disposables:h.add(new $s)};return e.set(c.vscodeWindowId,p),h.add(ni(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ve(c,Pi.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:rs},getDocument(c){return Tr(c).document}}})(),Uk=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 Ve(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ve(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){gu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Pi={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"},qk=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=jn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=jn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=jn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=jn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=jn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=jn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=jn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=jn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=jn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=jn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=jn(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=jn(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=jn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=jn(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 jn(e){return typeof e=="number"?`${e}px`:e}function To(e){return new qk(e)}var r0=class{constructor(){this._hooks=new $s,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(ni(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ve(o,Pi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ve(o,Pi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var So=class an extends dt{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(nn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ve(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ve(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ve(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:rs,disposables:this._store}))}static addTarget(t){if(!an.isTouchDevice())return dt.None;an.INSTANCE||(an.INSTANCE=new an);let i=an.INSTANCE.targets.push(t);return ni(i)}static ignoreTarget(t){if(!an.isTouchDevice())return dt.None;an.INSTANCE||(an.INSTANCE=new an);let i=an.INSTANCE.ignoreTargets.push(t);return ni(i)}static isTouchDevice(){return"ontouchstart"in rs||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=an.HOLD_DELAY&&Math.abs(p.initialPageX-Un(p.rollingPageX))<30&&Math.abs(p.initialPageY-Un(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=Un(p.rollingPageX),_.pageY=Un(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=Un(p.rollingPageX),x=Un(p.rollingPageY),b=Un(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>an.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=an.SCROLL_FRICTION*x,h+=an.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};So.SCROLL_FRICTION=-.005,So.HOLD_DELAY=700,So.CLEAR_TAP_COUNT_TIME=400,di([Wk],So,"isTouchDevice",1);var Gk=So,Zp=class extends dt{onclick(e,t){this._register(Ve(e,Pi.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ve(e,Pi.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ve(e,Pi.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ve(e,Pi.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ve(e,Pi.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ve(e,Pi.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ve(e,Pi.INPUT,t))}onblur(e,t){this._register(Ve(e,Pi.BLUR,t))}onfocus(e,t){this._register(Ve(e,Pi.FOCUS,t))}onchange(e,t){this._register(Ve(e,Pi.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Pi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Pi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Vk=class ip{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 ip(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 ip(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}}},Kk=class extends dt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Zp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=To(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(Ve(this.domNode.domNode,Pi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=To(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(Ve(this.slider.domNode,Pi.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=Fk(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(e0&&c>e2){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()}},a0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{constructor(e,t,i){super(),this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Ce),this.onWillScroll=this._onWillScroll.event,this._options=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=To(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=To(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=To(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 Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(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,Rr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ve(this._listenOnDomNode,Pi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Rr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Rr&&(t.className+=" mac"),t}var ap=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 Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(nn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ni(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ni(()=>this._styleElement.remove())),this._register(nn.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(f=>this._handleScroll(f)))}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}};ap=di([Re(2,_n),Re(3,ss),Re(4,Hy),Re(5,pl),Re(6,bn),Re(7,as)],ap);var lp=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(ni(()=>{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()}};lp=di([Re(1,_n),Re(2,ss),Re(3,$o),Re(4,as)],lp);var c2=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)}},kr={full:0,left:0,center:0,right:0},Os={full:0,left:0,center:0,right:0},uo={full:0,left:0,center:0,right:0},ju=class extends dt{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ni(()=>{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);Os.full=this._canvas.width,Os.left=e,Os.center=t,Os.right=e,this._refreshDrawHeightConstants(),uo.full=1,uo.left=1,uo.center=1+Os.left,uo.right=1+Os.left+Os.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(uo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Os[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=di([Re(2,_n),Re(3,$o),Re(4,as),Re(5,bn),Re(6,pl),Re(7,ss)],ju);var me;(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=""))(me||(me={}));var bu;(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="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${me.ESC}\\`)(l0||(l0={}));var op=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)}}};op=di([Re(2,_n),Re(3,bn),Re(4,va),Re(5,as)],op);var Ii=0,Hi=0,Ui=0,ui=0,Db={css:"#00000000",rgba:0},Ti;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(Ti||(Ti={}));var ei;(e=>{function t(p,f){if(ui=(f.rgba&255)/255,ui===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Ii=v+Math.round((_-v)*ui),Hi=S+Math.round((x-S)*ui),Ui=N+Math.round((b-N)*ui);let M=Ti.toCss(Ii,Hi,Ui),E=Ti.toRgba(Ii,Hi,Ui);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ti.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Ii,Hi,Ui]=vu.toChannels(f),{css:Ti.toCss(Ii,Hi,Ui),rgba:f}}e.opaque=a;function o(p,f){return ui=Math.round(f*255),[Ii,Hi,Ui]=vu.toChannels(p.rgba),{css:Ti.toCss(Ii,Hi,Ui,ui),rgba:Ti.toRgba(Ii,Hi,Ui,ui)}}e.opacity=o;function c(p,f){return ui=p.rgba&255,o(p,ui*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ei||(ei={}));var li;(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 Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),Ti.toColor(Ii,Hi,Ui);case 5:return Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),ui=parseInt(a.slice(4,5).repeat(2),16),Ti.toColor(Ii,Hi,Ui,ui);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 Ii=parseInt(o[1]),Hi=parseInt(o[2]),Ui=parseInt(o[3]),ui=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ti.toColor(Ii,Hi,Ui,ui);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),[Ii,Hi,Ui,ui]=t.getImageData(0,0,1,1).data,ui!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ti.toRgba(Ii,Hi,Ui,ui),css:a}}e.toColor=s})(li||(li={}));var pn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(ui=(h&255)/255,ui===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Ii=x+Math.round((p-x)*ui),Hi=b+Math.round((f-b)*ui),Ui=v+Math.round((_-v)*ui),Ti.toRgba(Ii,Hi,Ui)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(es(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=es(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,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})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function es(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Us.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=Y,q=this._workCell;if(b.length>0&&Y===b[0][0]&&T){let Se=b.shift(),He=this._isCellInSelection(Se[0],t);for(O=Se[0]+1;O=Se[1]),T?(U=!0,q=new u2(this._workCell,e.translateToString(!0,Se[0],Se[1]),Se[1]-Se[0]),z=Se[1]-1,V=q.getWidth()):B=Se[1]}let xe=this._isCellInSelection(Y,t),j=i&&Y===o,D=F&&Y>=f&&Y<=_,X=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Se=>{X=!0});let C=q.getChars()||Us;if(C===" "&&(q.isUnderline()||q.isOverline())&&(C=" "),be=V*h-p.get(C,q.isBold(),q.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&he||!xe&&!he&&q.bg===H)&&(xe&&he&&v.selectionForeground||q.fg===A)&&q.extended.ext===W&&D===R&&be===re&&!j&&!U&&!X&&T){q.isInvisible()?E+=Us:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(H=q.bg,A=q.fg,W=q.extended.ext,R=D,re=be,he=xe,U&&o>=Y&&o<=z&&(o=Y),!this._coreService.isCursorHidden&&j&&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(q.isBold()&&se.push("xterm-bold"),q.isItalic()&&se.push("xterm-italic"),q.isDim()&&se.push("xterm-dim"),q.isInvisible()?E=Us:E=q.getChars()||Us,q.isUnderline()&&(se.push(`xterm-underline-${q.extended.underlineStyle}`),E===" "&&(E=" "),!q.isUnderlineColorDefault()))if(q.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Uo.toColorRGB(q.getUnderlineColor()).join(",")})`;else{let Se=q.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&q.isBold()&&Se<8&&(Se+=8),N.style.textDecorationColor=v.ansi[Se].css}q.isOverline()&&(se.push("xterm-overline"),E===" "&&(E=" ")),q.isStrikethrough()&&se.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=q.getFgColor(),ae=q.getFgColorMode(),oe=q.getBgColor(),K=q.getBgColorMode(),de=!!q.isInverse();if(de){let Se=Z;Z=oe,oe=Se;let He=ae;ae=K,K=He}let ge,Me,Pe=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Se=>{Se.options.layer!=="top"&&Pe||(Se.backgroundColorRGB&&(K=50331648,oe=Se.backgroundColorRGB.rgba>>8&16777215,ge=Se.backgroundColorRGB),Se.foregroundColorRGB&&(ae=50331648,Z=Se.foregroundColorRGB.rgba>>8&16777215,Me=Se.foregroundColorRGB),Pe=Se.options.layer==="top")}),!Pe&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,Pe=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Pe&&se.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],se.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ti.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:de?(Fe=v.foreground,se.push("xterm-bg-257")):Fe=v.background}switch(ge||q.isDim()&&(ge=ei.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:q.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],q,ge,void 0)||se.push(`xterm-fg-${Z}`);break;case 50331648:let Se=Ti.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,Se,q,ge,Me)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,q,ge,Me)||de&&se.push("xterm-fg-257")}se.length&&(N.className=se.join(" "),se.length=0),!j&&!U&&!X&&T?M++:N.textContent=E,be!==this.defaultSpacing&&(N.style.letterSpacing=`${be}px`),x.push(N),Y=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=ei.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]}};cp=di([Re(1,Fy),Re(2,bn),Re(3,ss),Re(4,va),Re(5,$o),Re(6,pl)],cp);function Mb(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}},g2=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 x2(){return new g2}var lf="xterm-dom-renderer-owner-",tr="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",ho="xterm-focus",au="xterm-selection",_2=1,up=class extends dt{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new Ce).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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ni(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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: ${ei.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}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ho} .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} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ei.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ei.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ei.multiplyOpacity(ei.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(ho),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ho),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=di([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,ss),Re(13,pl)],up);var hp=class extends dt{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Ce),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};hp=di([Re(2,bn)],hp);var o0=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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=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 S2(this._window)),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Ce),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(nn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ve(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ve(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}},S2=class extends dt{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new hl),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ni(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ve(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)}},w2=class extends dt{constructor(){super(),this.linkProviders=[],this._register(ni(()=>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 Qp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Qp(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])}}};dp=di([Re(0,as),Re(1,Hu)],dp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,Fo=Uu?"node":navigator.userAgent,qo=Uu?"node":navigator.platform,u0=Fo.includes("Firefox"),E2=Fo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Fo);function N2(){if(!h0)return 0;let e=Fo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(qo),j2=qo==="iPad",T2=qo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(qo),Jp=qo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Fo),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=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 hl),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new hl),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 Ce),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Ce),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Ce),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ni(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ni(()=>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()}};fp=di([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,$o),Re(6,_n),Re(7,ss),Re(8,pl)],fp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Lo(Math.abs(a-e),Bo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Lo(p,Bo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Lo(g0(e,t,e,t-_a(t,a),!1,a).length,Bo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Lo(c,Bo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Lo(g0(e,c,i,h,p==="C",a).length,Bo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Bo(e,t){let i=t?"O":"[";return me.ESC+i+e}function Lo(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 Lb(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 of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=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 sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Ce),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Ce),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ni(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&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=Lb(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=Qp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?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(),F2)}_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&&!(Au&&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,f=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+=O-1,p+=O-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):H>1&&(b+=H-1,h-=H-1),h--,M--}for(;E1&&(v+=H-1,p+=H-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let O=this._bufferService.cols-E.start;S-=O,N+=O}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};pp=di([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,as),Re(8,ss)],pp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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()}},Di=Object.freeze((()=>{let e=[li.toColor("#2e3436"),li.toColor("#cc0000"),li.toColor("#4e9a06"),li.toColor("#c4a000"),li.toColor("#3465a4"),li.toColor("#75507b"),li.toColor("#06989a"),li.toColor("#d3d7cf"),li.toColor("#555753"),li.toColor("#ef2929"),li.toColor("#8ae234"),li.toColor("#fce94f"),li.toColor("#729fcf"),li.toColor("#ad7fa8"),li.toColor("#34e2e2"),li.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:Ti.toCss(s,a,o),rgba:Ti.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ti.toCss(s,s,s),rgba:Ti.toRgba(s,s,s)})}return e})()),fa=li.toColor("#ffffff"),wo=li.toColor("#000000"),Pb=li.toColor("#ffffff"),Ib=wo,fo={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends dt{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new Ce),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:wo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:fo,selectionBackgroundOpaque:ei.blend(wo,fo),selectionInactiveBackgroundTransparent:fo,selectionInactiveBackgroundOpaque:ei.blend(wo,fo),scrollbarSliderBackground:ei.opacity(fa,.2),scrollbarSliderHoverBackground:ei.opacity(fa,.4),scrollbarSliderActiveBackground:ei.opacity(fa,.5),overviewRulerBorder:fa,ansi:Di.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=It(e.foreground,fa),t.background=It(e.background,wo),t.cursor=ei.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ei.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,fo),t.selectionBackgroundOpaque=ei.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ei.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ei.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ei.opacity(t.selectionBackgroundTransparent,.3)),ei.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ei.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ei.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ei.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ei.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Di.slice(),t.ansi[0]=It(e.black,Di[0]),t.ansi[1]=It(e.red,Di[1]),t.ansi[2]=It(e.green,Di[2]),t.ansi[3]=It(e.yellow,Di[3]),t.ansi[4]=It(e.blue,Di[4]),t.ansi[5]=It(e.magenta,Di[5]),t.ansi[6]=It(e.cyan,Di[6]),t.ansi[7]=It(e.white,Di[7]),t.ansi[8]=It(e.brightBlack,Di[8]),t.ansi[9]=It(e.brightRed,Di[9]),t.ansi[10]=It(e.brightGreen,Di[10]),t.ansi[11]=It(e.brightYellow,Di[11]),t.ansi[12]=It(e.brightBlue,Di[12]),t.ansi[13]=It(e.brightMagenta,Di[13]),t.ansi[14]=It(e.brightCyan,Di[14]),t.ansi[15]=It(e.brightWhite,Di[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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=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=X2[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?Is(i&2097151):""}isProtected(t){return this._data[t*ht+2]&536870912}loadCell(t,i){return lu=t*ht,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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]+=Is(i):a&2097151?(this._combined[t]=Is(a&2097151)+Is(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*cf=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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cOo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Oo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new Ce),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Li={},pa=Li.B;Li[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Li.A={"#":"£"};Li.B=void 0;Li[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Li.C=Li[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Li.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Li.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Li.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Li.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Li.E=Li[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Li.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Li.H=Li[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Li["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=ji.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=sr.fromCharData([0,Oy,1,0]),this._whitespaceCell=sr.fromCharData([0,Us,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new Co(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&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=ji);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 Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(ji),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 Co(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(ji),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(ji),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 H=this.ybase+this.y;if(H>=c&&H0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let H=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-H,N-H,H,!0),N-=H,N===0&&(S--,N=_[S]),E-=H,E===0){M--;let A=Math.max(M,0);E=Oo(p,A,this._cols)}}for(let H=0;H0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends dt{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Ce),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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,xp=class extends dt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};xp=di([Re(0,bn)],xp);var el={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends dt{constructor(e){super(),this._onOptionChange=this._register(new Ce),this.onOptionChange=this._onOptionChange.event;let t={...el};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(ni(()=>{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 el))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in el))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=el[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=el[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:el[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 aE(e){return e==="block"||e==="underline"||e==="bar"}function ko(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]&&ko(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=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 Ce),this.onData=this._onData.event,this._onUserInput=this._register(new Ce),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Ce),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ko(Fb),this.decPrivateModes=ko(qb)}reset(){this.modes=ko(Fb),this.decPrivateModes=ko(qb)}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))}};_p=di([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={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 uf(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 hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=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 Ce),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};bp=di([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[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]],lE=[[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]],Mi;function oE(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=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Ce,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 po=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 vp;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>po?po: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>po?po: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,po):t}},mo=[],dE=class{constructor(){this._state=0,this._active=mo,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=mo}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=mo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||mo,!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",Iu(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=mo,this._id=-1,this._state=0}}},$n=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+=Iu(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}},go=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=go,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}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=go,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||go,!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",Iu(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=go,this._ident=0}},Eo=new S0;Eo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=Eo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Eo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=Eo,this._data="",this._hitLimit=!1,i));return this._params=Eo,this._data="",this._hitLimit=!1,t}},pE=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})(),gE=class extends dt{constructor(e=mE){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 S0,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(ni(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},zs=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends dt{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ji.clone(),this._eraseAttrDataInternal=ji.clone(),this._onRequestBell=this._register(new Ce),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Ce),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Ce),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Ce),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Ce),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Ce),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Ce),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Ce),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Ce),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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new $n(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new $n(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new $n(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new $n(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new $n(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new $n(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new $n(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new $n(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new $n(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new $n(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new $n(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new $n(f=>this.restoreCursorColor(f))),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 f in Li)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>zs&&(o=this._parseStack.position+zs)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthzs)for(let f=o;f0&&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,O=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof Co&&x.copyCellsFrom(E,O,0,M,!1);O=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new $n(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 f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Uo.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=ji.fg,e.bg=ji.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|=ji.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=ji.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|=ji.fg&16777215,s.bg&=-67108864,s.bg|=ji.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.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(`${me.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=ji.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(!Zb(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(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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=ji.clone(),this._eraseAttrDataInternal=ji.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(`${me.ESC}${c}${me.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)}},yp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=di([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=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 Ce),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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},Sp=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)))}};Sp=di([Re(0,_n)],Sp);var iv=!1,kE=class extends dt{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new hl),this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Ce),this._instantiationService=new K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(nn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(nn.forward(this._bufferService.onResize,this._onResize)),this._register(nn.forward(this.coreService.onData,this._onData)),this._register(nn.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(nn.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Ce),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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ni(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.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=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=EE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.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=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var vi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(vi=this._search(t),vi===-1)||this._getKey(this._array[vi])!==t)return!1;do if(this._array[vi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vi),!0;while(++via-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&&(vi=this._search(e),!(vi<0||vi>=this._array.length)&&this._getKey(this._array[vi])===e))do yield this._array[vi];while(++vi=this._array.length)&&this._getKey(this._array[vi])===e))do t(this._array[vi]);while(++vi=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}},pf=0,nv=0,TE=class extends dt{constructor(){super(),this._decorations=new jE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new Ce),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Ce),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ni(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&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)}},rv=20,Du=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 DE(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(Ve(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ni(()=>{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===rv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;xa(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(Ve(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ve(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ve(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ve(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,xa(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}}};wp=di([Re(1,Wp),Re(2,as),Re(3,_n),Re(4,qy)],wp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new hl),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new hl),this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Ce),this.onKey=this._onKey.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Ce),this.onBell=this._onBell.event,this._onFocus=this._register(new Ce),this._onBlur=this._register(new Ce),this._onA11yCharEmitter=this._register(new Ce),this._onA11yTabEmitter=this._register(new Ce),this._onWillOpen=this._register(new Ce),this._setup(),this._decorationService=this._instantiationService.createInstance(TE),this._instantiationService.setService($o,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(nn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(nn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(nn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(nn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ni(()=>{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=ei.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ti.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ti.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(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.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(me.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(Ve(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ve(this.textarea,"paste",e)),this._register(Ve(this.element,"paste",e)),u0?this._register(Ve(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ve(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ve(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ve(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ve(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ve(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ve(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ve(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ve(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ve(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(Ve(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",Uf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ss,this._coreBrowserService),this._register(Ve(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ve(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(pl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(as,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(nn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ve(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ve(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(Ve(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.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){By(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=NE(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===me.ETX||i.key===me.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)&&(LE(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)}},sv=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 zE(t)}getNullCell(){return new sr}},PE=class extends dt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Ce),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Er=0,$E=class extends dt{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var FE=2,qE=1,WE=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,f=s-h,_=a-p-t;return{cols:Math.max(FE,Math.floor(_/e.css.cell.width)),rows:Math.max(qE,Math.floor(f/e.css.cell.height))}}};/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var $i=0,Fi=0,qi=0,hi=0,ln;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(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})(ln||(ln={}));var GE;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;$i=v+Math.round((_-v)*hi),Fi=S+Math.round((x-S)*hi),qi=N+Math.round((b-N)*hi);let M=ln.toCss($i,Fi,qi),E=ln.toRgba($i,Fi,qi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return ln.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[$i,Fi,qi]=Su.toChannels(f),{css:ln.toCss($i,Fi,qi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[$i,Fi,qi]=Su.toChannels(p.rgba),{css:ln.toCss($i,Fi,qi,hi),rgba:ln.toRgba($i,Fi,qi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var en;(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 $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),ln.toColor($i,Fi,qi);case 5:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),ln.toColor($i,Fi,qi,hi);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 $i=parseInt(o[1]),Fi=parseInt(o[2]),qi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),ln.toColor($i,Fi,qi,hi);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),[$i,Fi,qi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:ln.toRgba($i,Fi,qi,hi),css:a}}e.toColor=s})(en||(en={}));var mn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return $i=x+Math.round((p-x)*hi),Fi=b+Math.round((f-b)*hi),qi=v+Math.round((_-v)*hi),ln.toRgba($i,Fi,qi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,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})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e{let e=[en.toColor("#2e3436"),en.toColor("#cc0000"),en.toColor("#4e9a06"),en.toColor("#c4a000"),en.toColor("#3465a4"),en.toColor("#75507b"),en.toColor("#06989a"),en.toColor("#d3d7cf"),en.toColor("#555753"),en.toColor("#ef2929"),en.toColor("#8ae234"),en.toColor("#fce94f"),en.toColor("#729fcf"),en.toColor("#ad7fa8"),en.toColor("#34e2e2"),en.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:ln.toCss(s,a,o),rgba:ln.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:ln.toCss(s,s,s),rgba:ln.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!is(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&is(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&is(c,p)&&is(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=!C0(e,t),a=!is(e,t),o=!k0(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?!is(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(is(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&&(is(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!is(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",tl="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${tl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${tl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${tl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${tl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${tl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${tl}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,Fs="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Fs)||s.createObjectStore(Fs)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function il(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction(Fs,"readwrite");c.objectStore(Fs).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction(Fs,"readonly").objectStore(Fs).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction(Fs,"readwrite");a.objectStore(Fs).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Bi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[O,H]=w.useState(new Set),[A,W]=w.useState(null),[R,re]=w.useState(null),[he,be]=w.useState(!1),[B,se]=w.useState(!1),F=eN(x,_),Y=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const U=w.useCallback(K=>{var ge;const{width:de}=K.container.getBoundingClientRect();if(!(de<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[de,ge]of Bi)ge.container.style.display=de===K?"block":"none";if(K){const de=Bi.get(K);de&&setTimeout(()=>U(de),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const q=w.useRef({});w.useEffect(()=>{q.current=f||{}},[f]);const xe=w.useCallback((K,de,ge)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Pe=z.current[K]?"&bypass=true":"",Fe=q.current[K],Se=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${Pe}${Se}`);He.onopen=()=>{de.connected=!0,de._retried=!1,H(at=>{const et=new Set(at);return et.delete(K),et}),He.send(JSON.stringify({type:"resize",cols:de.term.cols,rows:de.term.rows}))};let Je=!0;He.onmessage=at=>{if(Je&&(Je=!1,typeof at.data=="string"&&at.data===QE)){de.term.reset(),mf(K).catch(()=>{});return}de.term.write(typeof at.data=="string"?lv(at.data):at.data)},He.onclose=at=>{if(de.connected=!1,de.ws===He){de.ws=null;try{const et=de.serialize.serialize();il(K,et).catch(()=>{})}catch{}if(at.code===4e3&&!de._retried){de._retried=!0,de.term.write(`\r +\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r +`),V.current(K,de,!1);return}H(et=>new Set(et).add(K))}},de.term.onData(at=>{He.readyState===WebSocket.OPEN&&He.send(at)}),de.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,de)=>{if(!S.current||Bi.has(K))return;const{resume:ge=!1,autoConnect:Me=!0}=de??{},Pe=document.createElement("div");Pe.style.width="100%",Pe.style.height="100%",Pe.style.display="none",Pe.style.paddingLeft="10px",Pe.style.boxSizing="border-box",S.current.appendChild(Pe);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),Se=new WE,He=new XE;Fe.loadAddon(Se),Fe.loadAddon(He),Fe.open(Pe);const Je={term:Fe,fit:Se,serialize:He,ws:null,container:Pe,observer:null,connected:!1},at=new ResizeObserver(()=>{var jt;const{width:et}=Pe.getBoundingClientRect();if(!(et<50))try{Se.fit(),((jt=Je.ws)==null?void 0:jt.readyState)===WebSocket.OPEN&&Je.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});at.observe(Pe),Je.observer=at,Bi.set(K,Je),E(et=>[...et,K]);try{const et=await rN(K);if(et){const jt=lv(et);Fe.write(jt),jt!==et&&il(K,jt).catch(()=>{})}}catch{}Me?xe(K,Je,ge):H(et=>new Set(et).add(K)),setTimeout(()=>U(Je),50)},[xe,U]),D=w.useCallback(async(K,de)=>{const ge=Bi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),de||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,de))},[xe]),X=w.useCallback(K=>{const de=Bi.get(K);if(de){try{const ge=de.serialize.serialize();il(K,ge).catch(()=>{})}catch{}de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),Bi.delete(K),E(ge=>ge.filter(Me=>Me!==K)),H(ge=>{const Me=new Set(ge);return Me.delete(K),Me}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const de=Bi.get(K);de&&(((ge=de.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&de.ws.send(`exit +`),mf(K).catch(()=>{}),de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),Bi.delete(K),E(Me=>Me.filter(Pe=>Pe!==K)),H(Me=>{const Pe=new Set(Me);return Pe.delete(K),Pe}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,de,ge)=>{const Me=Bi.get(K);if(!Me||Bi.has(de)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:de,...ge??{}})})).ok)return!1;Bi.delete(K),Bi.set(de,Me);try{const Fe=Me.serialize.serialize();await mf(K),await il(de,Fe)}catch{}return E(Fe=>Fe.map(Se=>Se===K?de:Se)),H(Fe=>{if(!Fe.has(K))return Fe;const Se=new Set(Fe);return Se.delete(K),Se.add(de),Se}),(Me.connected||Me.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(de)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),V.current(de,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if(F){T(null);return}if(Y){T(null);return}Bi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Bi.has(t)){const de=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!de}),T(t)}}).catch(()=>{Bi.has(t)||(j(t),T(t))})}},[t,j,T,F,Y]),w.useEffect(()=>{const K=setInterval(()=>{for(const[de,ge]of Bi)if(ge.connected)try{const Me=ge.serialize.serialize();il(de,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,de]of Bi){try{const ge=de.serialize.serialize();il(K,ge).catch(()=>{})}catch{}de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Bi.clear()},[]);const ae=t?O.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:de=>{de.stopPropagation(),K.startsWith("_new_")?W(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>W(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))?d.jsx("button",{onClick:()=>re(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!F&&!Y&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),be(!0),setTimeout(()=>be(!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"})]})]})]})}),Y&&!F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){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:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>W(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;W(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>re(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;re(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Wo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Wo.prototype.normal={};Wo.prototype.property={};Wo.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Wo(i,s,t)}function Cp(e){return e.toLowerCase()}class Rn{constructor(t,i){this.attribute=i,this.property=t}}Rn.prototype.attribute="";Rn.prototype.booleanish=!1;Rn.prototype.boolean=!1;Rn.prototype.commaOrSpaceSeparated=!1;Rn.prototype.commaSeparated=!1;Rn.prototype.defined=!1;Rn.prototype.mustUseProperty=!1;Rn.prototype.number=!1;Rn.prototype.overloadedBoolean=!1;Rn.prototype.property="";Rn.prototype.spaceSeparated=!1;Rn.prototype.space=void 0;let dN=0;const ot=ya(),Ni=ya(),kp=ya(),ve=ya(),Kt=ya(),ol=ya(),Fn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Ni,commaOrSpaceSeparated:Fn,commaSeparated:ol,number:ve,overloadedBoolean:kp,spaceSeparated:Kt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Rn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var nl={},xf,pv;function wN(){if(pv)return xf;pv=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=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var O=1,H=1;function A(V){var U=V.match(t);U&&(O+=U.length);var T=V.lastIndexOf(p);H=~T?V.length-T:H+V.length}function W(){var V={line:O,column:H};return function(U){return U.position=new R(V),be(),U}}function R(V){this.start=V,this.end={line:O,column:H},this.source=E.source}R.prototype.content=M;function re(V){var U=new Error(E.source+":"+O+":"+H+": "+V);if(U.reason=V,U.filename=E.source,U.line=O,U.column=H,U.source=M,!E.silent)throw U}function he(V){var U=V.exec(M);if(U){var T=U[0];return A(T),M=M.slice(T.length),U}}function be(){he(i)}function B(V){var U;for(V=V||[];U=se();)U!==!1&&V.push(U);return V}function se(){var V=W();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var U=2;x!=M.charAt(U)&&(_!=M.charAt(U)||f!=M.charAt(U+1));)++U;if(U+=2,x===M.charAt(U-1))return re("End of comment missing");var T=M.slice(2,U-2);return H+=2,A(T),M=M.slice(U),H+=2,V({type:b,comment:T})}}function F(){var V=W(),U=he(s);if(U){if(se(),!he(a))return re("property missing ':'");var T=he(o),z=V({type:v,property:N(U[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return he(c),z}}function Y(){var V=[];B(V);for(var U;U=F();)U!==!1&&(V.push(U),B(V));return V}return be(),Y()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return nl;mv=1;var e=nl&&nl.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(nl,"__esModule",{value:!0}),nl.default=i;const t=e(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return nl}var xo={},gv;function kN(){if(gv)return xo;gv=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return xo.camelCase=p,xo}var _o,xv;function EN(){if(xv)return _o;xv=1;var e=_o&&_o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,_o=s,_o}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(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 L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ao(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class cn 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=Ao(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}}cn.prototype.file="";cn.prototype.name="";cn.prototype.reason="";cn.prototype.message="";cn.prototype.stack="";cn.prototype.column=void 0;cn.prototype.line=void 0;cn.prototype.ancestors=void 0;cn.prototype.cause=void 0;cn.prototype.fatal=void 0;cn.prototype.place=void 0;cn.prototype.ruleId=void 0;cn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}zo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);zo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 zo(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 zo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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?(qn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(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 xn=qs(/[A-Za-z]/),on=qs(/[\dA-Za-z]/),JN=qs(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=qs(/\d/),e5=qs(/[\dA-Fa-f]/),t5=qs(/[!-/:-@[-`{-~]/);function We(e){return e!==null&&e<-2}function Wt(e){return e!==null&&(e<0||e===32)}function gt(e){return e===-2||e===-1||e===32}const Fu=qs(new RegExp("\\p{P}|\\p{S}","u")),ba=qs(/\s/);function qs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function xl(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 yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return gt(p)?(e.enter(i),h(p)):t(p)}function h(p){return gt(p)&&o++c))return;const re=t.events.length;let he=re,be,B;for(;he--;)if(t.events[he][0]==="exit"&&t.events[he][1].type==="chunkFlow"){if(be){B=t.events[he][1].end;break}be=!0}for(E(s),R=re;RH;){const W=i[A];t.containerState=W[1],W[0].exit.call(t,e)}i.length=H}function O(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function dl(e){if(e===null||Wt(e)||ba(e))return 1;if(Fu(e))return 2}function qu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,qn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&>(R)?yt(e,O,"linePrefix",o+1)(R):O(R)}function O(R){return R===null||We(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),H(R))}function H(R){return R===null||We(R)?(e.exit("codeFlowValue"),O(R)):(e.consume(R),H)}function A(R){return e.exit("codeFenced"),t(R)}function W(R,re,he){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),se}function se(U){return R.enter("codeFencedFence"),gt(U)?yt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),Y(U)):he(U)}function Y(U){return U===h?(be++,R.consume(U),Y):be>=c?(R.exit("codeFencedFenceSequence"),gt(U)?yt(R,V,"whitespace")(U):V(U)):he(U)}function V(U){return U===null||We(U)?(R.exit("codeFencedFence"),re(U)):he(U)}}}function _5(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 bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):We(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||We(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):We(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(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):We(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&bo(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),bo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bo(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Mu(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||We(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||Wt(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):We(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||We(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!gt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):We(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||We(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ro(e,t){let i;return s;function s(a){return We(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):gt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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 Wt(v)?Ro(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return gt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||We(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return Wt(h)?Ro(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return gt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||We(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return We(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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"},qn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(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||Wt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||We(_)?(e.exit("atxHeading"),t(_)):gt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Wt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:F:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||Wt(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):F(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?O(C):H(C))}return C===45||on(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function O(C){return gt(C)?(e.consume(C),O):B(C)}function H(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):gt(C)?(e.consume(C),H):B(C)}function A(C){return C===45||C===46||C===58||C===95||on(C)?(e.consume(C),A):W(C)}function W(C){return C===61?(e.consume(C),R):gt(C)?(e.consume(C),W):H(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,re):gt(C)?(e.consume(C),R):he(C)}function re(C){return C===p?(e.consume(C),p=null,be):C===null||We(C)?i(C):(e.consume(C),re)}function he(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Wt(C)?W(C):(e.consume(C),he)}function be(C){return C===47||C===62||gt(C)?H(C):i(C)}function B(C){return C===62?(e.consume(C),se):i(C)}function se(C){return C===null||We(C)?F(C):gt(C)?(e.consume(C),se):i(C)}function F(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):We(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,Y)(C)):C===null||We(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),F)}function Y(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||We(C)?Y(C):(e.enter("htmlFlowData"),F(C))}function T(C){return C===45?(e.consume(C),j):F(C)}function z(C){return C===47?(e.consume(C),c="",q):F(C)}function q(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):F(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),q):F(C)}function xe(C){return C===93?(e.consume(C),j):F(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):F(C)}function D(C){return C===null||We(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return We(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Go,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),W):j===63?(e.consume(j),H):xn(j)?(e.consume(j),he):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),O):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):We(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):We(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function O(j){return j===null||j===62?T(j):We(j)?(c=O,z(j)):(e.consume(j),O)}function H(j){return j===null?i(j):j===63?(e.consume(j),A):We(j)?(c=H,z(j)):(e.consume(j),H)}function A(j){return j===62?T(j):H(j)}function W(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||on(j)?(e.consume(j),R):re(j)}function re(j){return We(j)?(c=re,z(j)):gt(j)?(e.consume(j),re):T(j)}function he(j){return j===45||on(j)?(e.consume(j),he):j===47||j===62||Wt(j)?be(j):i(j)}function be(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):We(j)?(c=be,z(j)):gt(j)?(e.consume(j),be):T(j)}function B(j){return j===45||j===46||j===58||j===95||on(j)?(e.consume(j),B):se(j)}function se(j){return j===61?(e.consume(j),F):We(j)?(c=se,z(j)):gt(j)?(e.consume(j),se):be(j)}function F(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,Y):We(j)?(c=F,z(j)):gt(j)?(e.consume(j),F):(e.consume(j),V)}function Y(j){return j===a?(e.consume(j),a=void 0,U):j===null?i(j):We(j)?(c=Y,z(j)):(e.consume(j),Y)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||Wt(j)?be(j):(e.consume(j),V)}function U(j){return j===47||j===62||Wt(j)?be(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),q}function q(j){return gt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||We(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),gt(f)?yt(e,h,"whitespace")(f):h(f))}}const An={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Go,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return gt(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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Go,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!gt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(An,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(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!gt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),gt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||We(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Go,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++i0){const Yt=Be.tokenStack[Be.tokenStack.length-1];(Yt[1]||Av).call(Be,void 0,Yt[0])}for(_e.position={start:Ps(te.length>0?te[0][1].start:{line:1,column:1,offset:0}),end:Ps(te.length>0?te[te.length-2][1].end:{line:1,column:1,offset:0})},Ke=-1;++Ke0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=xl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:xl(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 aT(e,t){const i={src:xl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:xl(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 cT(e,t){const i={href:xl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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 dT(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=nm(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Do=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 Wu:case iS:return i(c,a);case Do:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),rl="",{toString:CT}={},{keys:kT}=Object,vo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Do,rl];case"Object":return[Bu,rl];case"Date":return[um,rl];case"RegExp":return[hm,rl];case"Map":return[dm,rl];case"Set":return[fm,rl];case"DataView":return[Do,i]}return i.includes("Array")?[Do,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(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]=vo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Do:{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 Bu:{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 kT(c))(e||!cu(vo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(vo(b))||cu(vo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(vo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Po=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let O=typeof i=="string"?i:i(p,v);typeof O=="string"&&(O={type:"text",value:O}),S.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(O)?O:[O]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const O=M.children[M.children.length-1];O&&O.type==="text"?O.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Po(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 Gu=(function(e){if(e==null)return MT;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?AT(e):RT(e);if(typeof e=="string")return DT(e);throw new Error("Expected function, string, or object as test")});function AT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` +`}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var yf,Hv;function WT(){if(Hv)return yf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,O=!1;for(typeof N=="boolean"&&(O=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Yo(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 XT(e){if(Yo(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 ZT(e){Yo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 Yo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&O.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?O.push(...R):R&&O.push(R),S=A+H[0].length,E=!0),!b.global)break;H=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=H)}N.push(O)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=O),v[x]=O),b[x]=H}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(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 oR(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 cR(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 uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=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),f(),_}function hR(e,t,i){return(i?"":" ")+e}function gm(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 dR(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Io(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=dl(e),a=dl(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`,after:` +`});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 f=i.containerPhrasing(e,{before:"# ",after:` +`,...o.current()});return/^[\t ]/.test(f)&&(f=Io(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function xm(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 wR(e){const t=xm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):xm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Df,tableHeader:Df,tableRow:Df}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),O=f([E]);return O.slice(0,O.indexOf(` +`))}function p(v,S,N,M){const E=N.enter("tableCell"),O=N.enter("phrasing"),H=N.containerPhrasing(v,{...M,before:o,after:o});return O(),E(),H}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const O=[],H=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=dr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||Wt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(dr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Wt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||Wt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=dr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Wt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Go,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=dl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[se][1].type;if(V==="lineEnding"||V==="linePrefix")se--;else break}const F=se>-1?s.events[se][1].type:null,Y=F==="tableHead"||F==="tableRow"?R:p;return Y===R&&s.parser.lazy[s.now().line]?i(B):Y(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):We(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):gt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||Wt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,gt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):W(B)}function N(B){return gt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||We(B)?A(B):W(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),O(B)):W(B)}function O(B){return B===45?(e.consume(B),O):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),H):(e.exit("tableDelimiterFiller"),H(B))}function H(B){return gt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||We(B)?!c||a!==o?W(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):W(B)}function W(B){return i(B)}function R(B){return e.enter("tableRow"),re(B)}function re(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),re):B===null||We(B)?(e.exit("tableRow"),t(B)):gt(B)?yt(e,re,"whitespace")(B):(e.enter("data"),he(B))}function he(B){return B===null||B===124||Wt(B)?(e.exit("data"),re(B)):(e.consume(B),B===92?be:he)}function be(B){return B===92||B===124?(e.consume(B),he):he(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},sl(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=sl(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 sl(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Wt(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 We(p)?t(p):gt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],fl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["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"]},Hs={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...fl,...t}:fl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Vo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Vo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Hs.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const cl=["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"],ns=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(cl.map(e=>[IS(e),e])),P3={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 Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 No(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,O=Math.max(1,_-E),H=a.fontWeight??400,A=iy((re,he)=>e(re,he,H),t,f,N),W=A.length*N*o,R=A.every(re=>e(re,N,H)<=f+.5);return{lines:A,ok:W<=O&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function ul(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=ul(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=ul(t.lineHeightFactor,.9,2),c=ul(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 Vu(e){if(!e||typeof e!="object")return;const t=e,i=ul(t.paddingX,0,.25),s=ul(t.paddingY,0,.25),a=ul(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 jo(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(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 $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:O,half:H}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:O-H,y:E},base2:{x:O+H,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 du=.05;function Wi(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Wi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Wi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Wi(t.x)&&Wi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Wi(b.x)&&Wi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Wi(t.x)&&Wi(t.y)&&Wi(t.width)&&Wi(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=vm(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=Vu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Wi(e==null?void 0:e.x)&&Wi(e==null?void 0:e.y)&&Wi(e==null?void 0:e.width)&&Wi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 yo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(O=>!_[O]),v=O=>s.needClean>0?yo(O,s.needClean):"no image cuts",S={plan:yo(s.total,s.total),clean:v(s.withClean),letter:yo(s.withText,s.total),export:yo(s.exported,s.total),upload:yo(s.uploaded,s.total),publish:null},N=x.map((O,H)=>({key:O,label:cD[O],status:b===-1||HVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Cm=[{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:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(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 ll(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ll(e.current)}function km(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Tn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Yt,fi,Rt,St,Ht,nt,Xt;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let $=!1;return Y(!1),(async()=>{try{const{ensureFontsReady:we}=await uy(async()=>{const{ensureFontsReady:Ee}=await import("./export-cut-m_bbvXgX.js");return{ensureFontsReady:Ee}},[]);await we([b.family,v.family])}catch{}$||Y(!0)})(),()=>{$=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),O=E.invalid.length,[H,A]=w.useState(!1),W=O===0&&E.changed&&E.overlays.length>0,[R,re]=w.useState(()=>E.overlays),[he,be]=w.useState(()=>ll(E.overlays)),B=w.useRef(null),se=w.useCallback($=>(we,Ee,Ae=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ye=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ye?(Ye.font=`${Ae} ${Ee}px ${$}`,Ye.measureText(we).width):we.length*Ee*.5},[]),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,z]=w.useState(!1),[q,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),de=w.useRef(null),ge=w.useCallback(()=>{const $=oe.current;if(!$)return;const we=$.clientWidth,Ee=$.clientHeight;let Ae,Ye;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ae=At.width,Ye=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ae=At.naturalWidth,Ye=At.naturalHeight}if(!we||!Ee)return;const Ue=Math.min(we/Ae,Ee/Ye),ut=Ae*Ue,vt=Ye*Ue;ae({x:(we-ut)/2,y:(Ee-vt)/2,width:ut,height:vt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const $=oe.current;if(!$)return;const we=new ResizeObserver(()=>ge());return we.observe($),()=>we.disconnect()},[ge]);const Me=w.useCallback($=>{const we=WS($.type,$.x,$.y),Ee=we.width,Ae=Math.max(.08,1-$.y);if(!$.text||!F||Z.width<=0)return we;const Ye=$.type==="sfx"?N:S,Ue=Tn(Ee,Z.width);let ut=$.type==="sfx"?.08:.12;for(let vt=0;vt<24;vt++){const At=Math.min(ut,Ae),Bt=Tn(At,Z.height);if(!No(se(Ye),$.text,Ue,Bt,jo({...$},Z.height||300,Ue,Bt)).overflow||At>=Ae)return{width:Ee,height:At};ut+=.03}return{width:Ee,height:Math.min(ut,Ae)}},[F,Z,se,S,N]),Pe=w.useCallback($=>{const we=Lp($,.1+Math.random()*.3,.1+Math.random()*.3),Ee={...we,...Me(we)};re(Ae=>[...Ae,Ee]),U(Ee.id)},[Me]),Fe=w.useCallback($=>{const Ee={...Lp($.type,.1+Math.random()*.3,.1+Math.random()*.3),text:$.text,...$.type==="speech"&&$.speaker?{speaker:$.speaker}:{}},Ae={...Ee,...Me(Ee)};re(Ye=>[...Ye,Ae]),U(Ae.id)},[Me]),Se=w.useCallback(($,we)=>{re(Ee=>Ee.map(Ae=>Ae.id===$?{...Ae,...we}:Ae))},[]),He=w.useCallback($=>{var ut;const we=Z.height||300,Ee=Z.width>0?Tn($.width,Z.width):200,Ae=Z.height>0?Tn($.height,Z.height):100,Ye=$.type==="sfx"?N:S,Ue=No(se(Ye),$.text,Ee,Ae,jo({...$,textStyle:void 0},we,Ee,Ae));Se($.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,we),fontWeight:((ut=$.textStyle)==null?void 0:ut.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,se,Se]),Je=w.useCallback($=>{re(we=>we.filter(Ee=>Ee.id!==$)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),et=w.useCallback(($,we)=>{$.stopPropagation(),U(we),z(!1)},[]),jt=w.useCallback(($,we,Ee)=>{$.stopPropagation(),$.preventDefault();const Ae=R.find(Ye=>Ye.id===we);Ae&&(U(we),de.current={id:we,mode:Ee,startX:$.clientX,startY:$.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const $=Ee=>{const Ae=de.current;if(!Ae||Z.width===0)return;const Ye=dy(Ee.clientX-Ae.startX,Z.width),Ue=dy(Ee.clientY-Ae.startY,Z.height);if(Ae.mode==="move"){const ut=pu(Ae.origX+Ye,0,1-Ae.origW),vt=pu(Ae.origY+Ue,0,1-Ae.origH);Se(Ae.id,{x:ut,y:vt})}else{const ut=pu(Ae.origW+Ye,py,1-Ae.origX),vt=pu(Ae.origH+Ue,py,1-Ae.origY);Se(Ae.id,{width:ut,height:vt})}},we=()=>{de.current=null};return window.addEventListener("mousemove",$),window.addEventListener("mouseup",we),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",we)}},[Z,Se]);const Oe=w.useCallback(async()=>{var $;C(null);try{const we=ll(R),Ee=(($=t.aiDraft)==null?void 0:$.status)==="generated"&&we!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ee??null),f&&a()}catch(we){C(we instanceof Error?we.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(O>0&&!H){const $=O;D(`${$} overlay${$===1?"":"s"} from the cut plan ${$===1?"has":"have"} no usable position and cannot be exported — re-place ${$===1?"it":"them"} or discard ${$===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:$,ensureFontsReady:we}=await uy(async()=>{const{exportCut:Vt,ensureFontsReady:rn}=await import("./export-cut-m_bbvXgX.js");return{exportCut:Vt,ensureFontsReady:rn}},[]),Ee=R.some(Vt=>Vt.type==="sfx"),Ae=[b.family,...Ee?[v.family]:[]],{ready:Ye,missing:Ue}=await we(Ae);if(!Ye){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const ut=M.url,vt=await $(ut,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=vt.type==="image/webp"?"webp":"jpg";At.append("file",vt,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)be(ll(R)),o==null||o();else{const Vt=await Ut.json();D(Vt.error||"Export failed")}}catch($){D($ instanceof Error?$.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,O,H]),je=R.find($=>$.id===V),Gt=w.useMemo(()=>X3(R),[R]),yi=w.useRef(t.id);w.useEffect(()=>{yi.current!==t.id&&(yi.current=t.id,be(ll(E.overlays)))},[t.id,E.overlays]);const kt=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:he,current:R}),Xe=w.useMemo(()=>SD({...t,overlays:R},{staleExport:kt}),[t,R,kt]),te=w.useMemo(()=>km(t),[t]),_e=w.useMemo(()=>{const $={};for(const we of R){const Ee=F3(we);let Ae=!1;if(F&&Z.width>0&&we.text){const Ye=we.type==="sfx"?N:S,Ue=Tn(we.width,Z.width),ut=Tn(we.height,Z.height);Ae=No(se(Ye),we.text,Ue,ut,jo(we,Z.height||300,Ue,ut)).overflow}(Ee||Ae)&&($[we.id]={outOfBounds:Ee,overflow:Ae})}return $},[R,F,Z,se,S,N]),Be=Object.keys(_e).length,$e=t.kind==="text",Ke=!t.cleanImagePath;return!$e&&Ke&&R.length===0&&!t.narration&&!((Yt=t.dialogue)!=null&&Yt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Pe("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"}),d.jsx("button",{onClick:()=>Pe("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"}),d.jsx("button",{onClick:()=>Pe("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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:q,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:q?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Oe()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),O>0&&!H?d.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:[d.jsxs("span",{children:[O," overlay",O===1?"":"s"," ","from the cut plan ",O===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",O===1?"it":"them",", or"]}),d.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 ",O," unplaceable overlay",O===1?"":"s"]})]}):O>0?d.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 ",O," unplaceable overlay",O===1?"":"s"," — the export will not include"," ",O===1?"it":"them","."]}):W?d.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,Gt.length>0&&d.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,": ",Gt.length," bubble"," ",Gt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Gt.map($=>`#${$.indexA+1} ${Lf(R[$.indexA])} ↔ #${$.indexB+1} ${Lf(R[$.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",Xe.hasCleanImage],["script-text","Script text",Xe.hasScriptText],["bubbles",`Bubbles placed${Xe.bubblesPlaced?` (${Xe.bubblesPlaced})`:""}`,Xe.bubblesPlaced>0],["exported","Final exported",Xe.exported],["uploaded","Uploaded",Xe.uploaded]].map(([$,we,Ee])=>d.jsxs("span",{"data-testid":`lettering-check-${$}`,"data-done":Ee?"true":"false",className:`flex items-center gap-1 ${Ee?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ee?"✓":"○"}),we]},$))}),kt&&d.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."}),Be>0&&d.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:[Be," bubble",Be===1?"":"s"," may not export cleanly:"," ",Object.entries(_e).map(([$,we])=>{const Ee=R.findIndex(Ye=>Ye.id===$),Ae=[we.outOfBounds?"outside image":null,we.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ee+1} ${Lf(R[Ee])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:$=>{if($&&Z.width===0){const we=$.getBoundingClientRect();we.width>0&&ae({x:0,y:0,width:we.width,height:we.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map($=>{if($.type!=="speech")return null;const we=Z.x+Tn($.x,Z.width),Ee=Z.y+Tn($.y,Z.height),Ae=Tn($.width,Z.width),Ye=Tn($.height,Z.height),Ue=$S($,Ae,Ye),ut=$.tailAnchor?ym(we,Ee,Ae,Ye,$.tailAnchor,Ue):null,vt=Math.max(1.5,Z.height*.004),At=$.id===V;return d.jsx("path",{"data-testid":`balloon-${$.id}`,d:qS(we,Ee,Ae,Ye,ut,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?vt+.5:vt,strokeLinejoin:"round"},$.id)})}),Z.width>0&&R.map($=>{const we=Z.x+Tn($.x,Z.width),Ee=Z.y+Tn($.y,Z.height),Ae=Tn($.width,Z.width),Ye=Tn($.height,Z.height),Ue=$.id===V,ut=$.type==="speech",vt=$.type==="narration",At=!!_e[$.id];return d.jsxs("div",{"data-testid":`overlay-${$.id}`,"data-warning":At?"true":"false",onClick:Bt=>et(Bt,$.id),onMouseDown:Bt=>jt(Bt,$.id,"move"),className:`absolute rounded cursor-move select-none ${ut?"":`border-2 ${kD[$.type]}`} ${vt?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!ut?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:we,top:Ee,width:Ae,height:Ye},children:[(()=>{var rn,ri;const Bt=$.type==="sfx"?N:S;if(!$.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[$.type]});const Ut=$.type!=="sfx"&&!!$.speaker;if(!F)return d.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(Ye*.05,16)),fontWeight:((rn=$.textStyle)==null?void 0:rn.fontWeight)??400},"data-testid":`overlay-text-${$.id}`,"data-fonts-ready":"false",children:Ut?`${$.speaker}: ${$.text}`:$.text});const Vt=No(se(Bt),$.text,Ae,Ye,jo($,Z.height,Ae,Ye));return d.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-${$.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Vt.speakerFontSize,lineHeight:1.2},children:$.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Vt.fontSize,lineHeight:`${Vt.lineHeight}px`,fontWeight:((ri=$.textStyle)==null?void 0:ri.fontWeight)??400},children:Vt.lines.map((vn,Wn)=>d.jsx("span",{className:"block",children:vn},Wn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),jt(Bt,$.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${$.id}`})]},$.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((fi=t.aiDraft)==null?void 0:fi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),te.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:te.map($=>d.jsxs("button",{onClick:()=>Fe($),"data-testid":`script-insert-${$.key}`,title:`Add ${$.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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[$.type]]})," ",d.jsxs("span",{className:"text-muted",children:[$.speaker?`${$.speaker}: `:"",$.text.length>32?`${$.text.slice(0,32)}…`:$.text]})]},$.key))})]}),je?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[je.type]}),je.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:je.speaker||"",onChange:$=>Se(je.id,{speaker:$.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:je.text,onChange:$=>Se(je.id,{text:$.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"})]}),d.jsx("button",{onClick:()=>Se(je.id,Me(je)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=je.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>Se(je.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"}):d.jsx("button",{type:"button",onClick:()=>He(je),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"})]}),((St=je.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((je.textStyle.fontScale??.032)*100).toFixed(1),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(je.textStyle.fontWeight??400),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",fontWeight:$.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(je.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat($.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"})]}),je.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(je.textStyle.speakerScale??.8).toFixed(2),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat($.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),je.type==="speech"&&(()=>{const $=je.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(we=>d.jsx("button",{type:"button",onClick:()=>Se(je.id,{tailAnchor:we.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-${we.key}`,children:we.label},we.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:$.x,onChange:we=>Se(je.id,{tailAnchor:{...$,x:parseFloat(we.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:$.y,onChange:we=>Se(je.id,{tailAnchor:{...$,y:parseFloat(we.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"})]})]})]})})(),je.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Ht=je.bubbleStyle)==null?void 0:Ht.paddingX)??.06)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((nt=je.bubbleStyle)==null?void 0:nt.paddingY)??.08)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Xt=je.bubbleStyle)==null?void 0:Xt.cornerRadius)??.4)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat($.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",je.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",je.x.toFixed(3),", y:"," ",je.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",je.width.toFixed(3),", h:"," ",je.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?Je(je.id):z(!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:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[O,H]=w.useState(!1),[A,W]=w.useState(()=>YS(h)??{width:800,height:600}),[R,re]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var se;try{(se=document.fonts)!=null&&se.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||H(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const se=new ResizeObserver(()=>{re({width:B.clientWidth,height:B.clientHeight})});return se.observe(B),()=>se.disconnect()},[]);const he=w.useCallback(B=>(se,F,Y=400)=>E?(E.font=`${Y} ${F}px ${B}`,E.measureText(se).width):se.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const se=B.currentTarget.naturalWidth||A.width,F=B.currentTarget.naturalHeight||A.height;se>0&&F>0&&W({width:se,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const se=B.x*R.width,F=B.y*R.height,Y=B.width*R.width,V=B.height*R.height,U=$S(B,Y,V),T=B.tailAnchor?ym(se,F,Y,V,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(se,F,Y,V,T,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var q;const se=B.x*R.width,F=B.y*R.height,Y=B.width*R.width,V=B.height*R.height,U=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:se,top:F,width:Y,height:V},children:B.text?O?(()=>{var j;const xe=No(he(U),B.text,Y,V,jo(B,R.height,Y,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((q=B.textStyle)==null?void 0:q.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` +`).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(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(` +`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(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 Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const O=await GD(e);E||o(O)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const O=await YD(e,E);await i(O)}catch(O){h(O instanceof Error?O.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(O=>O.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(O=>O.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(O=>O.status!=="done").length,M=p.reduce((O,H)=>O+H.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(O=>d.jsxs("li",{"data-testid":`finish-step-${O.key}`,"data-status":O.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${O.status==="current"?"border-accent/40 bg-accent/10 text-accent":O.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[O.status]}),d.jsx("span",{children:O.label}),O.detail&&d.jsxs("span",{className:"text-muted",children:["· ",O.detail]})]},O.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(O=>d.jsxs("div",{"data-testid":`finish-issue-group-${O.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:O.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:O.lines.map((H,A)=>d.jsx("li",{children:H},A))})]},O.key))})]})]})]})}function tM(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 Mo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:ll(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:gn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Mo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:O,converting:H,rowRef:A}){var Fe,Se;const W=w.useRef(null),[R,re]=w.useState(!1),[he,be]=w.useState(null),[B,se]=w.useState(!1),[F,Y]=w.useState(!1),[V,U]=w.useState(!1),[T,z]=w.useState(!1),q=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await O(e.id,E),z(!1),h())},[E,O,e.id,h]),X=w.useCallback(async He=>{re(!0),be(null);try{let Je=He;if(!n1(He))try{Je=await Ku(He)}catch(Oe){return be(Oe instanceof Error?Oe.message:"Could not import image"),!1}const at=Je.type==="image/jpeg"?"jpg":"webp",et=new FormData;et.append("file",new File([Je],`clean.${at}`,{type:Je.type}));const jt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:et});if(!jt.ok){const Oe=await jt.json();return be(Oe.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{re(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Mo(e),de=(((Se=e.overlays)==null?void 0:Se.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=rM(e),Pe=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Pe?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":de})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||H),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":de}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:T||H,"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:T?"Converting…":"Convert image"})]}),xe&&!j&&d.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:[S.map((He,Je)=>d.jsx("p",{className:"text-[11px] text-error",children:He},Je)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),se(!0),setTimeout(()=>se(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:W,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var at;const Je=(at=He.target.files)==null?void 0:at[0];Je&&X(Je),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=W.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(He=>!He),disabled:R,"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:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.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."}),q==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),Y(!0),setTimeout(()=>Y(!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:F?"Copied!":"Copy Codex task"})]}),q==="missing"&&f&&d.jsx("button",{onClick:_,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"}),he&&d.jsx("p",{className:"text-xs text-error mt-1",children:he})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,Je)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},Je))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var fr,pi,Zt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,O]=w.useState(null),[H,A]=w.useState(null),[W,R]=w.useState(null),[re,he]=w.useState(!1),[be,B]=w.useState([]),[se,F]=w.useState(!1),[Y,V]=w.useState(""),[U,T]=w.useState({markdownReady:!1,published:!1}),[z,q]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,de]=w.useState(null),[ge,Me]=w.useState(!1),[Pe,Fe]=w.useState(new Set),[Se,He]=w.useState(new Map),[Je,at]=w.useState(!1),[et,jt]=w.useState(null),[Oe,ct]=w.useState(!1),[je,Gt]=w.useState(null),yi=w.useRef(new Map),kt=w.useRef(null),Xe=t.replace(/\.md$/,"");w.useEffect(()=>{var Q;c&&kt.current!==c.seq&&(kt.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),Gt(c.cutId)),(Q=S.current)==null||Q.call(S))},[c]),w.useEffect(()=>(p==null||p(W!==null),()=>p==null?void 0:p(!1)),[W,p]),w.useEffect(()=>{var P;if(je==null)return;const Q=yi.current.get(je);Q&&((P=Q.scrollIntoView)==null||P.call(Q,{behavior:"smooth",block:"center"}),Gt(null))},[je,x]);const te=w.useCallback(async()=>{var Q;try{const P=await i(`/api/stories/${e}/cuts/${Xe}`);if(P.status===404){b(null);return}if(!P.ok){const ye=await P.json();O(ye.error||"Failed to load cuts");return}const ce=await P.json();b(ce),O(null);try{const ye=await i(`/api/stories/${e}/${t}`);if(ye.ok){const Te=await ye.json(),De=typeof(Te==null?void 0:Te.content)=="string"?Te.content:"",Le=Array.isArray(ce==null?void 0:ce.cuts)?ce.cuts:[],tt=De.length>0&&KS(De,Le).ready,ft=(Te==null?void 0:Te.status)==="published"||(Te==null?void 0:Te.status)==="published-not-indexed";T({markdownReady:tt,published:ft})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(Q=v.current)==null||Q.call(v)}catch{O("Failed to load cuts")}finally{M(!1)}},[i,e,Xe,t]),_e=w.useCallback(async Q=>!!(await i(`/api/stories/${e}/cuts/${Xe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).ok,[i,e,Xe]),Be=w.useCallback(async()=>{at(!1);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/detect-clean-images`);if(!Q.ok)return;const P=await Q.json();Fe(new Set(Array.isArray(P.detected)?P.detected:[]));const ce=new Map,ye=P.stale;if(Array.isArray(ye))for(const Te of ye){if(typeof(Te==null?void 0:Te.cutId)!="number"||typeof(Te==null?void 0:Te.message)!="string")continue;const De=ce.get(Te.cutId)??[];De.push(Te.message),ce.set(Te.cutId,De)}He(ce),at(!0)}catch{}},[i,e,Xe]),$e=w.useCallback(async()=>{jt(null);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/asset-diagnostics`);if(!Q.ok)return;const P=await Q.json();jt(Array.isArray(P.diagnostics)?P.diagnostics:null)}catch{}},[i,e,Xe]),Ke=w.useCallback(async()=>{ct(!0);try{await Promise.all([te(),Be(),$e()])}finally{ct(!1)}},[te,Be,$e]),Yt=w.useCallback(async(Q,P={})=>{var Te;if(!x)return!1;const ce=x.cuts.find(De=>De.id===Q);if(!ce||!Mo(ce)||(((Te=ce.overlays)==null?void 0:Te.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const ye=hy(ce);if(ye.length===0)return oe(`Cut ${ce.id}: no script lines available to draft.`),!1;de(Q),oe(null);try{const De={...x,cuts:x.cuts.map(tt=>tt.id===Q?{...tt,overlays:ye,aiDraft:_y(ye)}:tt)};return await _e(De)?(oe(`Cut ${ce.id}: AI draft ready`),await te(),P.openEditor&&R(Q),!0):(oe(`Cut ${ce.id}: AI draft failed`),!1)}finally{de(null)}},[x,_e,te]),fi=w.useCallback(async()=>{if(!x)return;const Q=x.cuts.filter(P=>{var ce;return Mo(P)&&(((ce=P.overlays)==null?void 0:ce.length)??0)===0&&!P.finalImagePath&&!P.uploadedCid&&!P.uploadedUrl});if(Q.length===0){oe("No unlettered cuts need an AI draft");return}Me(!0),oe(null);try{const P={...x,cuts:x.cuts.map(ye=>{if(!Q.some(De=>De.id===ye.id))return ye;const Te=hy(ye);return Te.length>0?{...ye,overlays:Te,aiDraft:_y(Te)}:ye})};if(!await _e(P)){oe("AI draft failed");return}oe(`AI draft ready for ${Q.length} cut${Q.length===1?"":"s"}`),await te()}finally{Me(!1)}},[x,_e,te]),Rt=w.useCallback(async()=>{q(!0),oe(null),B([]);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/sync-clean-images`,{method:"POST"}),P=await Q.json().catch(()=>({}));if(!Q.ok)oe(P.error||"Sync failed");else{const ce=Array.isArray(P.synced)?P.synced.length:0,ye=Array.isArray(P.cleared)?P.cleared.length:0,Te=Array.isArray(P.rejected)?P.rejected:[];Te.length>0&&B(Te.map(Le=>`Cut ${Le.cutId}: ${Le.reason}`));const De=[];ce>0&&De.push(`Synced ${ce}`),ye>0&&De.push(`Cleared ${ye} stale path${ye===1?"":"s"}`),oe(De.length>0?De.join(", "):"No new clean images"),await te(),await Be(),await $e()}}catch{oe("Sync failed")}q(!1)},[i,e,Xe,te,Be,$e]),St=w.useCallback(async(Q,P)=>{try{const ce=await i(HS(e,P));if(!ce.ok)return!1;const ye=await ce.blob(),Te=await Ku(new File([ye],"clean.png",{type:ye.type||"image/png"})),De=Te.type==="image/jpeg"?"jpg":"webp",Le=new FormData;return Le.append("file",new File([Te],`clean.${De}`,{type:Te.type})),(await i(`/api/stories/${e}/cuts/${Xe}/upload-clean/${Q}`,{method:"POST",body:Le})).ok}catch{return!1}},[i,e,Xe]),Ht=w.useCallback(async Q=>{X(!0),Z(null);let P=0;const ce=[];for(const ye of Q)await St(ye.cutId,ye.pngPath)?P++:ce.push(ye.cutId);await Ke(),X(!1),Z(ce.length===0?`Converted ${P} image${P===1?"":"s"} to WebP`:`Converted ${P}; ${ce.length} failed (Cut ${ce.join(", ")}) — try Convert image on each`)},[St,Ke]),nt=w.useCallback(async()=>{var Te;if(!x)return;F(!0),V(""),B([]);const Q=x.cuts.filter(De=>De.finalImagePath&&!De.uploadedCid),P=[],ce=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:De})=>V(`Upload limit reached — waiting ${Math.round(De/1e3)}s before continuing…`)});for(let De=0;De{const $t=await i("/api/publish/upload-plot-image",{method:"POST",body:rt});if($t.ok){const{cid:hn,url:ar}=await $t.json();return{ok:!0,status:$t.status,cid:hn,url:ar}}const ti=await $t.json().catch(()=>({}));return{ok:!1,status:$t.status,errorMessage:ti.error}},{...a,onWaiting:({attempt:$t,maxRetries:ti,waitMs:hn})=>V(`Cut ${Le.id} rate-limited — waiting ${Math.round(hn/1e3)}s before retry ${$t}/${ti}...`)});if(!Ct.ok){P.push(`Cut ${Le.id}: upload failed — ${Ct.errorMessage||"unknown"}`);continue}const{cid:Ze,url:Si}=Ct;(await i(`/api/stories/${e}/cuts/${Xe}/set-uploaded/${Le.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Ze,url:Si})})).ok||P.push(`Cut ${Le.id}: failed to record upload`)}catch(tt){P.push(`Cut ${Le.id}: ${tt instanceof Error?tt.message:"failed"}`)}}if(P.length>0){B(P),F(!1),V(""),te();return}V("Preparing episode for publishing…");const ye=await i(`/api/stories/${e}/cuts/${Xe}/generate-markdown`,{method:"POST"});if(ye.ok){const De=await ye.json();((Te=De.warnings)==null?void 0:Te.length)>0&&B(De.warnings)}F(!1),V(""),te()},[x,i,e,Xe,a,te]),Xt=w.useCallback(async()=>{j(!0),oe(null);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/repair-asset-paths`,{method:"POST"}),P=await Q.json().catch(()=>({}));if(!Q.ok)oe(P.error||"Repair failed");else{const ce=Array.isArray(P.cleared)?P.cleared.length:0;oe(ce>0?`Cleared ${ce} stale path${ce===1?"":"s"}`:"No stale paths to clear"),await te(),await Be()}}catch{oe("Repair failed")}j(!1)},[i,e,Xe,te,Be]),[$,we]=w.useState(!1),Ee=w.useCallback(async(Q,P=!0)=>{if(x){we(!0);try{const ce=x.cuts.reduce((tt,ft)=>Math.max(tt,ft.id),0)+1,ye={id:ce,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"},Te=[...x.cuts];Te.splice(Math.max(0,Math.min(Q,Te.length)),0,ye);const De={...x,cuts:Te},Le=await i(`/api/stories/${e}/cuts/${Xe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(De)});if(Le.ok)P?R(ce):A(ce),await te();else{const tt=await Le.json().catch(()=>({}));oe(tt.error||"Could not add text panel")}}catch{oe("Could not add text panel")}we(!1)}},[x,i,e,Xe,te]),Ae=w.useCallback(()=>Ee((x==null?void 0:x.cuts.length)??0,!0),[Ee,x]);if(w.useEffect(()=>{te(),Be(),$e()},[te,Be,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Xe,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:te,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ye=W!==null?x.cuts.find(Q=>Q.id===W):null;if(Ye)return d.jsx(ND,{storyName:e,cut:Ye,plotFile:Xe,language:s,authFetch:i,targetLabel:gn(Ye)?`Between-scene card ${Ye.id}`:`Cut ${String(Ye.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(Q,P)=>{const ce={...x,cuts:x.cuts.map(Te=>Te.id===W?{...Te,overlays:Q,aiDraft:P??Te.aiDraft??null}:Te)};if(!await _e(ce))throw new Error("Failed to save overlays")},onExported:()=>te(),onClose:()=>{R(null),te()}});const Ue=x.cuts.reduce((Q,P)=>{const ce=r1(P);return Q[ce]++,Q},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),ut=x.cuts.filter(Q=>!gn(Q)).length,vt=x.cuts.filter(Q=>GS(Q)).map(Q=>Q.id),At=uD({cuts:x.cuts,published:U.published}),Bt=((fr=At.steps.find(Q=>Q.key==="upload"))==null?void 0:fr.status)==="done",Ut=x.cuts.some(Q=>Q.finalImagePath&&!Q.uploadedCid)||Bt&&!U.markdownReady,Vt=(et??[]).filter(Q=>Q.state==="needs-conversion"&&Q.convertiblePng).map(Q=>({cutId:Q.cutId,pngPath:Q.convertiblePng})),rn=new Map(Vt.map(Q=>[Q.cutId,Q.pngPath])),ri=(et??[]).filter(Q=>Q.state==="needs-conversion"&&Q.issue).map(Q=>Q.issue),vn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((pi=Xe.match(/\d+/))==null?void 0:pi[0])??"0",10)+1}`,Wn=typeof x.title=="string"?x.title:null,un=x.cuts.filter(Q=>!gn(Q)),yn={cuts:x.cuts.length,artwork:un.filter(Q=>Q.cleanImagePath||rn.has(Q.id)).length,converted:un.filter(Q=>Q.cleanImagePath&&/\.(webp|jpe?g)$/i.test(Q.cleanImagePath)).length,lettered:x.cuts.filter(Q=>{var P;return(((P=Q.overlays)==null?void 0:P.length)??0)>0||!!Q.finalImagePath}).length,uploaded:x.cuts.filter(Q=>Q.uploadedCid||Q.uploadedUrl).length},Sn=x.cuts.filter(Q=>{var P;return Mo(Q)&&(((P=Q.overlays)==null?void 0:P.length)??0)===0&&!Q.finalImagePath&&!Q.uploadedCid&&!Q.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:vn}),Wn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Wn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[yn.cuts," cuts · ",yn.artwork," artwork found ·"," ",yn.converted," converted · ",yn.lettered," ","lettered · ",yn.uploaded," uploaded"]})]}),Sn>0&&d.jsx("button",{onClick:fi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${Sn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{he(!0),B([]);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/generate-markdown`,{method:"POST"});if(Q.ok){const P=await Q.json();B(P.warnings||[])}}catch{}he(!1)},disabled:re,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:re?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:$,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:$?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Ke,disabled:Oe,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:Oe?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Rt,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"}),d.jsx("button",{onClick:nt,disabled:se||!(x!=null&&x.cuts.some(Q=>Q.finalImagePath&&!Q.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:Y||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),vt.length>0&&d.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:[vt.length===1?"Cut":"Cuts"," ",vt.join(", ")," ",vt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",vt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),Je&&ut>0&&Ue.missing===0&&Se.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",ut," clean image",ut===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Vt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Vt.length," PNG image",Vt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Ht(Vt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ri.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ri.map((Q,P)=>d.jsx("li",{children:Q},P))})]})]}),et&&et.length>0&&(()=>{const Q=tM(et),P=et.filter(ce=>ce.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",Q.uploaded," uploaded · ",Q.finalReady," final ·"," ",Q.cleanReady," clean · ",Q.planned," planned",Q.needsConversion>0?` · ${Q.needsConversion} needs conversion`:"",Q.missing>0?` · ${Q.missing} missing`:""]}),P.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:P.map(ce=>d.jsx("li",{children:ce.issue},ce.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:be,onFinish:nt,finishing:se,progressText:Y,canFinish:Ut,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((Q,P)=>{var ce;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:P,beforeLabel:P===0?"Episode opening":`After cut ${(ce=x.cuts[P-1])==null?void 0:ce.id}`,afterLabel:`Before cut ${Q.id}`,disabled:$,onAdd:()=>Ee(P)}),d.jsx(sM,{cut:Q,storyName:e,plotFile:Xe,language:s,expanded:H===Q.id,onToggle:()=>A(H===Q.id?null:Q.id),authFetch:i,onUpdated:()=>{te(),Be(),$e()},onOpenEditor:()=>R(Q.id),detectedLocalClean:Pe.has(Q.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Yt(Q.id,{openEditor:!0})},aiDrafting:K===Q.id,staleMessages:Se.get(Q.id)??[],onRepairStale:Xt,repairing:xe,conversionPng:rn.get(Q.id)??null,onConvert:St,converting:D,rowRef:ye=>{ye?yi.current.set(Q.id,ye):yi.current.delete(Q.id)}})]},Q.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Zt=x.cuts[x.cuts.length-1])==null?void 0:Zt.id}`,afterLabel:"Episode ending",disabled:$,onAdd:()=>Ee(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Ho(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 dM(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 Ip(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 Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...fl,attributes:{...fl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:O=null,onWorkflowActionHandled:H}){const[A,W]=w.useState(null),[R,re]=w.useState(!1),[he,be]=w.useState("preview"),[B,se]=w.useState("publish"),[F,Y]=w.useState("text"),[V,U]=w.useState(null),T=w.useCallback((ne,ke)=>{be("edit"),U(Ne=>({cutId:ne,openEditor:ke,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[z,q]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,de]=w.useState(""),[ge,Me]=w.useState(""),[Pe,Fe]=w.useState(!1),[Se,He]=w.useState(null),[Je,at]=w.useState(0),[et,jt]=w.useState(0),[Oe,ct]=w.useState(null),[je,Gt]=w.useState(null),[yi,kt]=w.useState(null),[Xe,te]=w.useState(0),_e=w.useRef(null),Be=w.useRef(!1),[$e,Ke]=w.useState(!1),[Yt,fi]=w.useState(cl[0]),[Rt,St]=w.useState(ns[0]),[Ht,nt]=w.useState(!1),[Xt,$]=w.useState(null),[we,Ee]=w.useState(null),[Ae,Ye]=w.useState(!1),[Ue,ut]=w.useState(!1),[vt,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Vt,rn]=w.useState(!1),ri=w.useRef(null),vn=w.useRef(null),[Wn,un]=w.useState(!1),[yn,Sn]=w.useState(null),[fr,pi]=w.useState(null),[Zt,Q]=w.useState("unknown"),P=w.useRef(!1),[ce,ye]=w.useState(!1),[Te,De]=w.useState(!1),[Le,tt]=w.useState(null),[ft,wt]=w.useState([]),[rt,Ct]=w.useState(null),Ze=w.useRef(null),Si=w.useRef(null),Br=w.useRef(0),$t=w.useCallback(async()=>{if(!e||!t){W(null);return}const ne=`${e}/${t}`,ke=Si.current!==ne;ke&&(Si.current=ne);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const it=await Ne.json();W(it),(ke||!Be.current)&&(q(it.content??""),ke&&(X(!1),Be.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{re(!0),$t().finally(()=>re(!1))},[$t]),w.useEffect(()=>{if(!e||!t||he==="edit"&&D)return;const ne=setInterval($t,3e3);return()=>clearInterval(ne)},[e,t,$t,he,D]);const[ti,hn]=w.useState(null),ar=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!ar||!e){hn(null);return}let ne=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ke=>ke.ok?ke.json():null).then(ke=>{ne||hn(ke?Op(ke.cuts||[]):null)}).catch(()=>{ne||hn(null)}),()=>{ne=!0}},[ar,e,i]);const os=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!os||!e||!t){He(null),at(0),jt(0),ct(null);return}let ne=!1;const ke=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[Ne,it]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ke}`)]);if(ne)return;if(!it.ok){He("error"),at(0),jt(0),ct(null);return}const Lt=await it.json(),gi=Lt.cuts||[],vr=Ne.ok?(await Ne.json()).content??"":"",xi=XS(vr,gi);ne||(He(xi.stage),at(xi.awaitingCount),jt(xi.totalCuts),ct(Op(gi)),kt(typeof Lt.title=="string"?Lt.title:null))}catch{ne||(He("error"),at(0),jt(0),ct(null))}})(),()=>{ne=!0}},[os,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,Xe]),w.useEffect(()=>{if(!e){Gt(null);return}let ne=!1;return i(`/api/stories/${e}/structure.md`).then(ke=>ke.ok?ke.json():null).then(ke=>{ne||Gt((ke==null?void 0:ke.content)??null)}).catch(()=>{}),()=>{ne=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ne=Cu(p);let ke=ne??"";if(!ne&&je){const it=je.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);it&&(ke=Cu(it[1].replace(/\*+/g,"").trim())??"")}de(ke);let Ne=h&&ns.find(it=>it.toLowerCase()===h.toLowerCase())||"";if(!Ne&&je){const it=je.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);it&&(Ne=ns.find(Lt=>Lt.toLowerCase()===it[1].replace(/\*+/g,"").trim().toLowerCase())||"")}Me(Ne),Fe(f??!1)},[e,p,h,f,je]);const Ws=w.useCallback(ne=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}).catch(()=>{})},[e,i]),Ft=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Be.current=!1,W(ke=>ke&&{...ke,content:z}))}catch{}j(!1)}},[e,t,i,z]),Dn=w.useCallback(async()=>{if(!e||!t)return;const ne=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ne}/generate-markdown`,{method:"POST"})).ok&&(await $t(),te(Ne=>Ne+1))}catch{}},[e,t,i,$t]);w.useEffect(()=>{if(O&&O.seq!==Br.current){switch(Br.current=O.seq,O.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":be("edit"),Y("cuts");break;case"generate-markdown":Dn();break;case"publish":be("preview");break}H==null||H(O.seq)}},[O,x,Dn,H]);const Yi=w.useCallback(ne=>{var it;const ke=(it=ne.target.files)==null?void 0:it[0];if(!ke)return;P.current=!0,Sn(null),pi(null);const Ne=Sy(ke);if(Ne){$(null),Ee(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ri.current&&(ri.current.value=""),Ut(Ne),Q("invalid");return}$(ke),Ee(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(ke))),Ut(null),Q("selected")},[]),Ai=w.useCallback(async ne=>{var Ne;const ke=(Ne=ne.target.files)==null?void 0:Ne[0];if(vn.current&&(vn.current.value=""),!(!ke||!e)){P.current=!0,Sn(null),un(!0),Ut(null);try{let it;try{it=await Ku(ke)}catch(dn){$(null),Ee(Ys=>(Ys&&URL.revokeObjectURL(Ys),null)),Ut(dn instanceof Error?dn.message:"Could not import image");return}const Lt=it.type==="image/jpeg"?"jpg":"webp",gi=new File([it],`cover.${Lt}`,{type:it.type}),vr=new FormData;vr.append("file",gi);const xi=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:vr});if(!xi.ok){const dn=await xi.json().catch(()=>({}));Ut(dn.error||"Cover import failed");return}$(gi),Ee(dn=>(dn&&URL.revokeObjectURL(dn),URL.createObjectURL(gi))),pi(null),Q("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{un(!1)}}},[e,i]),pr=w.useCallback(async ne=>{if(ne.size>1024*1024){tt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ne.type)){tt("Only WebP and JPEG images are accepted");return}De(!0),tt(null);try{const Ne=new FormData;Ne.append("file",ne);const it=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!it.ok){const gi=await it.json();throw new Error(gi.error||"Upload failed")}const Lt=await it.json();wt(gi=>[...gi,{cid:Lt.cid,url:Lt.url}])}catch(Ne){tt(Ne instanceof Error?Ne.message:"Upload failed")}finally{De(!1),Ze.current&&(Ze.current.value="")}},[i]),si=w.useCallback(ne=>{var Ne;const ke=(Ne=ne.target.files)==null?void 0:Ne[0];ke&&pr(ke)},[pr]),Mn=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ye(!0),Ut(null),rn(!1);try{let ne;if(Xt){const Ne=new FormData;Ne.append("file",Xt);const it=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!it.ok){const gi=await it.json();throw new Error(gi.error||"Cover upload failed")}ne=(await it.json()).cid}const ke=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...ne!==void 0&&{coverCid:ne},genre:Yt,language:Rt,isNsfw:Ht})});if(!ke.ok){const Ne=await ke.json();throw new Error(Ne.error||"Update failed")}rn(!0),$(null),ne!==void 0&&(At(!0),Ee(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Q("unknown"),ri.current&&(ri.current.value="")),setTimeout(()=>rn(!1),3e3)}catch(ne){Ut(ne instanceof Error?ne.message:"Update failed")}finally{Ye(!1)}}},[A==null?void 0:A.storylineId,Xt,Yt,Rt,Ht,i]);w.useEffect(()=>{Ke(!1),$(null),Ee(null),Ut(null),rn(!1),ut(!1),ye(!1),wt([]),tt(null),Sn(null),pi(null),Q("unknown"),P.current=!1,Y("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||P.current)return;let ne=!1;return(async()=>{try{const ke=await i(`/api/stories/${e}/cover-asset`);if(ne||!ke.ok)return;const Ne=await ke.json();if(ne)return;if(!(Ne!=null&&Ne.found)){Q("none");return}if(!Ne.valid){pi(Ne.error||"Detected cover asset is invalid and was not used"),Q("invalid");return}const it=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ne||!it.ok)return;const Lt=await it.blob(),gi=new File([Lt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(Sy(gi)||ne||P.current)return;$(gi),Ee(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(gi))),Sn(Ne.path),Q("detected")}catch{}})(),()=>{ne=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;ut(!1);const ne="https://plotlink.xyz";let ke=!1;return fetch(`${ne}/api/storyline/${A.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!ke){if(!Ne){Ut("Could not load current story metadata");return}if(Ne.genre){const it=Cu(Ne.genre);it&&fi(it)}if(Ne.language){const it=ns.find(Lt=>Lt.toLowerCase()===Ne.language.toLowerCase());it&&St(it)}Ne.isNsfw!==void 0&&nt(!!Ne.isNsfw),At(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),ut(!0)}}).catch(()=>{ke||Ut("Could not load current story metadata")}),()=>{ke=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(he!=="edit")return;const ne=ke=>{(ke.metaKey||ke.ctrlKey)&&ke.key==="s"&&(ke.preventDefault(),Ft())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[he,Ft]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const ne=new Date(A.publishedAt).getTime(),ke=300*1e3,Ne=()=>{const Lt=Math.max(0,ke-(Date.now()-ne));oe(Lt)};Ne();const it=setInterval(Ne,1e3);return()=>clearInterval(it)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const Gs=ae!==null&&ae<=0,mr=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Oi=(he==="edit"?z:(A==null?void 0:A.content)??"").length,mi=t==="genesis.md",gr=t?/^plot-\d+\.md$/.test(t):!1,Vi=c==="cartoon"&&gr,Ki=c==="cartoon"&&mi,cs=Ki||Vi,Lr=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",Or=S&&cs,Ko=Ki?ti?ti.total:null:Vi?Se===null?null:et:null,wa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Lr,cutCount:Ko,cutProgress:Ki?ti:null}),_l=(Ki||Vi)&&!Lr,zr=_l?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:je,contentType:"cartoon",episodeTitle:yi}):null,bl=!!zr&&Ho(zr,t),Xo=Vi&&!Lr&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:yi}),xr=Ki&&!Lr?wm((A==null?void 0:A.content)??""):null,Gn=!!xr&&xr.blockers.length>0,vl="w-full max-w-[32rem] rounded-xl border px-3 py-3",yl={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Pr=ne=>{if(!Ki)return null;const ke=cM({hasSelectedCover:!!Xt,invalid:Zt==="invalid",attached:ne});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ke.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${yl[ke.tone]}`,children:ke.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},_r=bl||Xo,Zo=()=>{if(!_l||!zr)return null;const ne=mi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":bl?"true":"false","data-blocked":_r?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ne,":"]})," ",d.jsx("span",{className:_r?"text-error font-medium":"text-foreground",children:zr})]}),bl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",mi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Xo?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",zr,"” 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]})},Sl=()=>xr?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Gn?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),xr.blockers.map((ne,ke)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ne},`b-${ke}`)),xr.warnings.map((ne,ke)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ne},`w-${ke}`))]}):null,us=mi||gr?1e4:null,br=!Lr&&us!==null&&Oi>us,lr=(A==null?void 0:A.content)??"",hs=Lr?{count:0,warnings:[]}:yM(lr),ds=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:_e,value:z,onChange:ne=>{q(ne.target.value),X(!0),Be.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:Ft,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Or&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${br?"text-error font-medium":"text-muted"}`,children:[Oi.toLocaleString(),us!==null?`/${us.toLocaleString()}`:" chars"]}),br&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Oi-us).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>be("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${he==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>be("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${he==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),he==="preview"?Vi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:Se}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Vi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>te(ne=>ne+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Ki?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>Y("text"),className:`px-2 py-0.5 text-[11px] rounded ${F==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>Y("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${F==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:F==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>te(ne=>ne+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):ds})]}):ds,!Or&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:wa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Gs&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),$t())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${mr?` (${mr})`:""}`}),gr&&d.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,K,ge,Pe)},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"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:Gs?gr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gr?"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."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var Ne;const ne=`https://plotlink.xyz/story/${A.storylineId}`;if(!gr)return ne;const ke=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ne}/${ke}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),mi&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Ke(ne=>!ne),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&mi&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Pr(vt),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{$(null),Ee(null),pi(null),Q("unknown"),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:Yi,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Yt,onChange:ne=>fi(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:cl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))}),d.jsx("select",{value:Rt,onChange:ne=>St(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ns.map(ne=>d.jsx("option",{value:ne,children:ne},ne))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Ht,onChange:ne=>nt(ne.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Mn,disabled:Ae||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ae?"Saving...":Ue?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Vi&&Oe&&Oe.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Oe.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.withClean,"/",Oe.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.withText,"/",Oe.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.uploaded,"/",Oe.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Ki&&ti&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ti.total," planned",ti.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ti.withClean," clean ·"," ",ti.withText," lettered ·"," ",ti.exported," exported ·"," ",ti.uploaded," uploaded"]})]}),(Ki||Vi)&&wa&&d.jsxs("div",{className:`${vl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Ko===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Ki?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:wa})]}),gr&&!Vi&&he==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ce,onChange:ne=>ye(ne.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),ce&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 ne;return(ne=Ze.current)==null?void 0:ne.click()},onDragOver:ne=>{ne.preventDefault(),ne.stopPropagation()},onDrop:ne=>{var Ne;ne.preventDefault(),ne.stopPropagation();const ke=(Ne=ne.dataTransfer.files)==null?void 0:Ne[0];ke&&pr(ke)},children:[d.jsx("input",{ref:Ze,type:"file",accept:"image/webp,image/jpeg",onChange:si,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Te?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Le&&d.jsx("span",{className:"text-error text-xs",children:Le}),ft.map((ne,ke)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ne.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ne.url})`),Ct(ke),setTimeout(()=>Ct(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:rt===ke?"Copied!":"Copy"})]})]},ne.cid))]})]}),mi&&c!=="cartoon"&&!(he==="edit"&&F==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Pr(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{P.current=!0,Sn(null),pi(null),Q("unknown"),$(null),Ee(ne=>(ne&&URL.revokeObjectURL(ne),null)),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:Yi,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:vn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Ai,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ne;return(ne=vn.current)==null?void 0:ne.click()},disabled:Wn,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:Wn?"Importing…":"Import generated image (PNG ok)"}),Xt&&d.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."}),yn&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",yn," — pick a file to override."]}),fr&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[fr," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Zt==="none"&&!Xt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!cs&&Zo(),!cs&&Sl(),!cs&&d.jsxs("div",{className:"flex items-center gap-2",children:[mi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:ne=>{de(ne.target.value),ne.target.value&&Ws({genre:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),cl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:ne=>{Me(ne.target.value),ne.target.value&&Ws({language:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ns.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(hs.count>0){const ke=`This plot contains ${hs.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(ke))return}const ne=mi?Xt:null;ne?await(s==null?void 0:s(e,t,K,ge,Pe,ne))&&(P.current=!0,Sn(null),pi(null),Q("unknown"),$(null),Ee(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),ri.current&&(ri.current.value="")):s==null||s(e,t,K,ge,Pe)},disabled:!!a||br||_r||Gn||mi&&(!K||!ge)||Vi&&Se!=="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"}),mi&&c==="cartoon"&&(!K||!ge)&&d.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"}),mi&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),mi&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),br&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Vi&&Se==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Vi&&Se==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Vi&&Se==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",Je," of ",et," ","still need an uploaded image"]})]}),cs&&d.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 →"}),hs.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:hs.warnings.map((ne,ke)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ne},ke))}),mi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Pe,onChange:ne=>{Fe(ne.target.checked),Ws({isNsfw:ne.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),Pe&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,O]=w.useState("cartoon"),[H,A]=w.useState("unknown"),[W,R]=w.useState(!1),[re,he]=w.useState(!1),[be,B]=w.useState(null),[se,F]=w.useState(!1),[Y,V]=w.useState(null),[U,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),he(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&ns.find(de=>de.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),O(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const q=w.useCallback(async()=>{R(!0),he(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)he(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){F(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(Pe){B(Pe instanceof Error?Pe.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",de=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",de);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!Me.ok){const Pe=await Me.json().catch(()=>({}));B(Pe.error||"Cover import failed.");return}A("present"),V(Pe=>(Pe&&URL.revokeObjectURL(Pe),URL.createObjectURL(de)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;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.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=H==="present"?"Cover set":H==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=H==="present"?"text-green-700":H==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.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:[d.jsx("option",{value:"",children:"Needs metadata"}),cl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(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:[d.jsx("option",{value:"",children:"Needs metadata"}),ns.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[Y&&d.jsx("img",{src:Y,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("button",{type:"button",onClick:j,"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:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),he(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:q,disabled:W,"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:W?"Saving…":"Save Story Info"}),re&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var et,jt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[O,H]=w.useState(null),[A,W]=w.useState(null),[R,re]=w.useState(null),[he,be]=w.useState(null),B=async()=>{try{const Oe=await t(`/api/stories/${e}/cover-asset`),ct=Oe.ok?await Oe.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const je=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!je.ok)return null;const Gt=await je.blob();return new File([Gt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||Gt.type})}catch{return null}};w.useEffect(()=>{let Oe=!1;return(async()=>{v(!0),N(!1);try{const je=await t(`/api/stories/${e}/progress`),Gt=je.ok?await je.json():null;if(Oe)return;!Gt||!Array.isArray(Gt.episodes)?(N(!0),x(null)):x(Gt),v(!1)}catch{Oe||(N(!0),x(null),v(!1))}})(),()=>{Oe=!0}},[e,t,f]);const se=((jt=(et=_==null?void 0:_.episodes)==null?void 0:et.find(Oe=>!Oe.published))==null?void 0:jt.file)??null,F=se==="genesis.md",Y=JSON.stringify([se??"",f]),[V,U]=w.useState(null);if(V!==Y&&(U(Y),H(null),W(null),re(null),be(null)),w.useEffect(()=>{if(!se)return;let Oe=!1;const ct=se.replace(/\.md$/,"");return(async()=>{var je;try{const Gt=[t(`/api/stories/${e}/${se}`),t(`/api/stories/${e}/cuts/${ct}`)];F&&Gt.push(t(`/api/stories/${e}/structure.md`));const[yi,kt,Xe]=await Promise.all(Gt);if(Oe)return;if(H(yi.ok?(await yi.json()).content??"":""),kt.ok){const te=await kt.json();if(Oe)return;W(Array.isArray(te.cuts)?te.cuts:[]),re(typeof te.title=="string"?te.title:null)}else W(null),re(null);be(F&&Xe&&Xe.ok?((je=await Xe.json())==null?void 0:je.content)??null:null)}catch{Oe||(H(""),W(null),re(null),be(null))}})(),()=>{Oe=!0}},[se,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Oe=>!Oe.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=T.cuts,q=_.cover==="present",xe=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:q?"done":"todo",detail:q?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=O!==null,oe=ae?Nm({fileName:T.file,fileContent:O??"",storySlug:e,structureContent:he,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Ho(oe,T.file),de=!X&&ae&&!Em({fileContent:O??"",episodeTitle:R}),ge=K||de,Me=X&&ae?wm(O??""):null,Pe=!!Me&&Me.blockers.length>0,Fe=!X&&ae&&A!==null?XS(O??"",A):null,Se=Fe&&Fe.stage==="error"?Fe.issues:[],Je=j&&C&&(ae&&(X||A!==null))&&!ge&&!Pe&&!Z&&!!a,at=async()=>{if(!(!Je||!a)){E(null);try{const Oe=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Oe)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Oe,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Oe.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Oe.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Oe.status==="done"?"✓":"○"}),d.jsx("span",{className:Oe.status==="done"?"text-foreground":"text-muted",children:Oe.label}),Oe.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Oe.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):de?d.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]}),Me&&d.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":Pe?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),Me.blockers.map((Oe,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Oe},`b-${ct}`)),Me.warnings.map((Oe,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Oe},`w-${ct}`))]}),Se.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(Se).map(Oe=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Oe.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Oe.title})},Oe.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:Se.map((Oe,ct)=>d.jsx("li",{className:"font-mono break-words",children:Oe},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!q&&d.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)"}),X&&!C&&d.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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.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 ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!Je,"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:Je?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||Pe?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Pe?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.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 qM(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 WM(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?Ho(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=qM(i,s);return a?Ho(a,t)||Ip(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,If=224,Hf=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[O,H]=w.useState(VM),[A,W]=w.useState([]),[R,re]=w.useState(!1),[he,be]=w.useState(""),[B,se]=w.useState(""),[F,Y]=w.useState(""),[V,U]=w.useState("English"),[T,z]=w.useState("normal"),[q,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[de,ge]=w.useState(new Set),[Me,Pe]=w.useState(new Set),[Fe,Se]=w.useState({}),[He,Je]=w.useState({}),[at,et]=w.useState({}),[jt,Oe]=w.useState({}),[ct,je]=w.useState({}),[Gt,yi]=w.useState({}),[kt,Xe]=w.useState(!1),[te,_e]=w.useState(!0),[Be,$e]=w.useState(null),Ke=w.useRef(new Map),Yt=w.useRef(new Map),fi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Ht=w.useRef(null),nt=w.useRef(null),Xt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(P=>P.ok?P.json():null).then(P=>{P!=null&&P.address&&E(P.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(P=>P.ok?P.json():null).then(P=>{P&&D(P)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(O))}catch{}},[O]),w.useEffect(()=>{const P=()=>{if(!nt.current)return;const ce=nt.current.getBoundingClientRect().width-If-Hf;H(ye=>jy(ye,ce))};return window.addEventListener("resize",P),P(),()=>window.removeEventListener("resize",P)},[]);const $=w.useCallback(()=>{be(""),se(""),Y(""),z("normal"),xe("claude"),re(!0)},[]),we=w.useCallback(async(P,ce,ye,Te)=>{const De=he.trim();if(!De)return;const Le=P==="cartoon"?"codex":Te;try{const tt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:ce,genre:F||void 0,contentType:P,agentMode:ye,agentProvider:Le})});if(!tt.ok)return;const ft=await tt.json();re(!1),Se(wt=>({...wt,[ft.name]:P})),Je(wt=>({...wt,[ft.name]:ce})),F&&et(wt=>({...wt,[ft.name]:F})),K(wt=>({...wt,[ft.name]:Le})),ye==="bypass"&&ae(wt=>({...wt,[ft.name]:!0})),s(ft.name),o(null)}catch{}},[t,he,B,F]);w.useEffect(()=>{if(A.length===0)return;const P=setInterval(async()=>{try{const ce=await t("/api/stories");if(!ce.ok)return;const ye=await ce.json(),Te=new Set(ye.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of Te)if(!St.current.has(De)&&A.length>0){const Le=A[0],tt=Ke.current.get(Le)||"fiction",ft=Yt.current.get(Le)||"English",wt=fi.current.get(Le)||"normal",rt=Rt.current.get(Le)||"claude";let Ct=!1;Ht.current&&(Ct=await Ht.current(Le,De,{contentType:tt,language:ft,agentMode:wt,agentProvider:rt}).catch(()=>!1)),Ct&&(W(Ze=>Ze.slice(1)),Ke.current.delete(Le),Yt.current.delete(Le),fi.current.delete(Le),Rt.current.delete(Le),wt==="bypass"&&ae(Ze=>{const Si={...Ze,[De]:!0};return delete Si[Le],Si}),K(Ze=>{const Si={...Ze,[De]:rt};return delete Si[Le],Si}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:tt,language:ft,agentMode:wt,agentProvider:rt})}).catch(()=>{})),s(De),o(null)}St.current=Te}catch{}},3e3);return()=>clearInterval(P)},[t,A]),w.useEffect(()=>{t("/api/stories").then(P=>{if(P.ok)return P.json()}).then(P=>{P!=null&&P.stories&&(St.current=new Set(P.stories.filter(ce=>ce.name!=="_example").map(ce=>ce.name)))}).catch(()=>{})},[t]);const Ee=w.useCallback((P,ce)=>{s(P),o(ce),h(null)},[]),Ae=w.useRef(null),Ye=w.useCallback(async P=>{var ce,ye,Te,De;Ae.current=P,s(P),o(null),h(null);try{const Le=await t(`/api/stories/${P}`);if(Le.ok&&Ae.current===P){const tt=await Le.json();if(tt.contentType==="cartoon")return;const ft=tt.files||[],rt=((ce=ft.map(Ct=>{var Ze;return{file:Ct.file,num:(Ze=Ct.file.match(/^plot-(\d+)\.md$/))==null?void 0:Ze[1]}}).filter(Ct=>Ct.num!=null).sort((Ct,Ze)=>parseInt(Ze.num)-parseInt(Ct.num))[0])==null?void 0:ce.file)??((ye=ft.find(Ct=>Ct.file==="genesis.md"))==null?void 0:ye.file)??((Te=ft.find(Ct=>Ct.file==="structure.md"))==null?void 0:Te.file)??((De=ft[0])==null?void 0:De.file);rt&&Ae.current===P&&o(rt)}}catch{}},[t]),Ue=w.useCallback(P=>{P.preventDefault(),Xt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const ce=Te=>{if(!Xt.current||!nt.current)return;const De=nt.current.getBoundingClientRect(),Le=De.width-If-Hf,tt=Te.clientX-De.left-If;H(jy(tt/Le,Le))},ye=()=>{Xt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",ce),window.removeEventListener("mouseup",ye)};window.addEventListener("mousemove",ce),window.addEventListener("mouseup",ye)},[]),ut=w.useCallback(async(P,ce,ye,Te,De,Le)=>{var rt;f(ce),v("Reading file..."),N(null);let tt=!1,ft=null,wt=!1;try{const Ct=await t(`/api/stories/${P}/${ce}`);if(!Ct.ok)throw new Error("Failed to read file");const Ze=await Ct.json(),Si=Fe[P];let Br=null,$t=null;if(ce==="genesis.md")try{const Ft=await t(`/api/stories/${P}/structure.md`);Ft.ok&&(Br=(await Ft.json()).content??null)}catch{}else if(Si==="cartoon"&&ce.match(/^plot-\d+\.md$/))try{const Ft=await t(`/api/stories/${P}/cuts/${ce.replace(/\.md$/,"")}`);Ft.ok&&($t=(await Ft.json()).title??null)}catch{}const ti=Nm({fileName:ce,fileContent:Ze.content,storySlug:P,structureContent:Br,contentType:Si,episodeTitle:$t});if(Si==="cartoon"&&Ho(ti,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(()=>{f(null),v("")},6e3),!1;if(Si==="cartoon"&&ce.match(/^plot-\d+\.md$/)&&!Em({fileContent:Ze.content,episodeTitle:$t}))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(()=>{f(null),v("")},6e3),!1;if(Si==="cartoon"&&ce==="genesis.md"){const Ft=wm(Ze.content).blockers;if(Ft.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Ft[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let hn;if(ce.match(/^plot-\d+\.md$/)){if(pM(Ze)){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(()=>{f(null),v("")},6e3);return}try{const Ft=await t(`/api/stories/${P}`);if(Ft.ok){const Yi=(await Ft.json()).files.find(Ai=>Ai.file==="genesis.md"&&Ai.storylineId);hn=Yi==null?void 0:Yi.storylineId}}catch{}if(!hn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Ft=await t("/api/publish/preflight");if(Ft.ok){const Dn=await Ft.json();if(gM(Dn))return N(xM(Dn)),f(null),v(""),!1}}catch{}v("Publishing...");const ar=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:P,fileName:ce,title:ti,content:Ze.content,genre:ye,language:Te,isNsfw:De,storylineId:hn,...wy(Fe,P,hn)?{contentType:wy(Fe,P,hn)}:{}})});if(!ar.ok){const Ft=await ar.json();throw new Error(Ft.error||"Publish failed")}const os=(rt=ar.body)==null?void 0:rt.getReader(),Ws=new TextDecoder;if(os)for(;;){const{done:Ft,value:Dn}=await os.read();if(Ft)break;const Ai=Ws.decode(Dn).split(` +`).filter(pr=>pr.startsWith("data: "));for(const pr of Ai)try{const si=JSON.parse(pr.slice(6));if(si.step&&v(si.message||si.step),si.step==="done"&&si.txHash){if(wt=!0,await t(`/api/stories/${P}/${ce}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:si.txHash,storylineId:si.storylineId,plotIndex:si.plotIndex,contentCid:si.contentCid,gasCost:si.gasCost,indexError:si.indexError,authorAddress:M})}),x(Mn=>Mn+1),Le&&ce==="genesis.md"&&si.storylineId){v("Uploading cover...");let Mn=null;try{Mn=await uM(t,si.storylineId,Le)}catch{}Mn||(tt=!0)}if(Si==="cartoon"&&si.storylineId)try{const Mn=ce!=="genesis.md",Gs=`storylineId=${si.storylineId}`+(Mn&&si.plotIndex!=null?`&plotIndex=${si.plotIndex}`:""),mr=await t(`/api/publish/public-title?${Gs}`);if(mr.ok){const Sa=await mr.json(),Oi=Mn?{plots:Sa.plotTitle!=null?[{plotIndex:si.plotIndex,title:Sa.plotTitle}]:[]}:{title:Sa.storylineTitle},mi=WM({fileName:ce,detail:Oi,plotIndex:si.plotIndex});mi.ok||(ft=GM(mi))}}catch{}}}catch{}}ft&&N(ft),v(tt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Ct){const Ze=Ct instanceof Error?Ct.message:"Publish failed";v(`Error: ${Ze}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return wt&&!tt},[t,Fe,M]),vt=w.useCallback(P=>{P.startsWith("_new_")&&(W(ce=>ce.filter(ye=>ye!==P)),Ke.current.delete(P),Yt.current.delete(P),fi.current.delete(P),Rt.current.delete(P),ae(ce=>{if(!(P in ce))return ce;const ye={...ce};return delete ye[P],ye}),K(ce=>{if(!(P in ce))return ce;const ye={...ce};return delete ye[P],ye}))},[]);w.useEffect(()=>{const P=ye=>{ge(new Set(ye.filter(rt=>rt.hasStructure).map(rt=>rt.name))),Pe(new Set(ye.filter(rt=>rt.hasGenesis).map(rt=>rt.name)));const Te={},De={},Le={},tt={},ft={},wt={};for(const rt of ye)Te[rt.name]=rt.contentType||"fiction",De[rt.name]=rt.language,Le[rt.name]=rt.genre,tt[rt.name]=rt.isNsfw,ft[rt.name]=rt.agentProvider,rt.title&&(wt[rt.name]=rt.title);Se(Te),Je(De),et(Le),Oe(tt),yi(ft),je(wt)};t("/api/stories").then(ye=>ye.ok?ye.json():null).then(ye=>{ye!=null&&ye.stories&&P(ye.stories)}).catch(()=>{});const ce=setInterval(async()=>{try{const ye=await t("/api/stories");if(ye.ok){const Te=await ye.json();P(Te.stories)}}catch{}},5e3);return()=>clearInterval(ce)},[t]);const At=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Bt=!!j&&!At,Ut=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const P=i;if((await t(`/api/stories/${P}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){yi(ye=>({...ye,[P]:"codex"})),K(ye=>({...ye,[P]:"codex"}));try{const ye=await t("/api/stories");if(ye.ok){const Te=await ye.json();if(Te!=null&&Te.stories){const De={};for(const Le of Te.stories)De[Le.name]=Le.agentProvider;yi(De)}}}catch{}}},[t,i]),rn=w.useCallback(P=>{i===P&&(s(null),o(null))},[i]),ri=i?oe[i]??Gt[i]:void 0,vn=Of(i,Fe,Ke.current),Wn=mM(vn,ri,i),un=!!i&&vn==="cartoon",yn=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",Sn=w.useCallback(P=>{const ce=i;if(ce)switch(P){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ee(ce,"structure.md");break;case"genesis":Ee(ce,"genesis.md");break;case"publish":h("publish");break}},[i,Ee]),fr=w.useCallback((P,ce)=>{const ye=i;if(!ye)return;const Te=De=>{$e(Le=>({action:De,seq:((Le==null?void 0:Le.seq)??0)+1}))};switch(P){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":if(!ce)return;Ee(ye,ce),Te(P);break}},[i,Ee]),pi=w.useCallback(P=>{i&&(P.genre!==void 0&&et(ce=>({...ce,[i]:P.genre||void 0})),P.language!==void 0&&Je(ce=>({...ce,[i]:P.language||void 0})),P.isNsfw!==void 0&&Oe(ce=>({...ce,[i]:P.isNsfw})))},[i]),Zt=w.useCallback(P=>{Xe(P),_e(!P)},[]),Q=kt&&!te;return d.jsxs("div",{ref:nt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Q?"stories-focused-lettering-mode":"stories-default-layout",children:[!Q&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ee,onNewStory:$,untitledSessions:A})}),!Q&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${O} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ye,onDestroySession:vt,onArchiveStory:rn,confirmedStories:de,renameRef:Ht,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Ke.current),needsProviderRepair:Wn,onRepairProvider:Vt})}),!Q&&d.jsx("div",{onMouseDown:Ue,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Q?{flex:"1 0 0"}:{flex:`${1-O} 0 0`},children:[!kt&&un&&i&&d.jsx(HM,{storyTitle:ct[i]||i,active:yn,onSelect:Sn}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:un&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:pi}):un&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:Ee}):un&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ee,onOpenStoryInfo:()=>h("story-info"),onPublish:ut,publishingFile:p,genre:at[i],language:He[i],isNsfw:jt[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:Ee}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:ut,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Ke.current)||"fiction",language:i?He[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?jt[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:P=>i&&Ee(i,P),onViewPublish:()=>h("publish"),focusedLetteringMode:kt,focusedLetteringWorkspaceVisible:te,onFocusedLetteringModeChange:Zt,onFocusedLetteringWorkspaceVisibleChange:_e,workflowActionRequest:Be,onWorkflowActionHandled:P=>$e(ce=>(ce==null?void 0:ce.seq)===P?null:ce)})}),!kt&&un&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:fr,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:he,onChange:P=>be(P.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:P=>se(P.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:P=>Y(P.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:[d.jsx("option",{value:"",children:"— Select later —"}),cl.map(P=>d.jsx("option",{value:P,children:P},P))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:P=>U(P.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:ns.map(P=>d.jsx("option",{value:P,children:P},P))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:P=>z(P.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:q,onChange:P=>xe(P.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:q==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!he.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>we("fiction",V,T,q),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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>we("cartoon",V,T,"codex"),disabled:Bt||!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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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."})]}),j&&!j.codex.installed&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Ut,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>re(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{zp as M,jo as a,$S as b,$D as c,$3 as d,No as l,ym as s,YS as t,n4 as v}; diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 2f6feda..7650250 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,7 +7,7 @@ - + From cca1cc765f2aafe9f2574243e82a10dc65584dfa Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:16:20 +0000 Subject: [PATCH 3/4] Make cartoon CTA requests monotonic --- app/web/components/StoriesPage.test.tsx | 9 +++ app/web/components/StoriesPage.tsx | 8 +- ...cut-m_bbvXgX.js => export-cut-33MiJugN.js} | 2 +- .../{index-OmkX9BzW.js => index-Ce_xoof_.js} | 74 +++++++++---------- app/web/dist/index.html | 2 +- 5 files changed, 53 insertions(+), 42 deletions(-) rename app/web/dist/assets/{export-cut-m_bbvXgX.js => export-cut-33MiJugN.js} (98%) rename app/web/dist/assets/{index-OmkX9BzW.js => index-Ce_xoof_.js} (57%) diff --git a/app/web/components/StoriesPage.test.tsx b/app/web/components/StoriesPage.test.tsx index b56f612..c85b644 100644 --- a/app/web/components/StoriesPage.test.tsx +++ b/app/web/components/StoriesPage.test.tsx @@ -1040,9 +1040,18 @@ describe("StoriesPage cartoon workflow nav routing (#439)", () => { action: "open-lettering", }), ); + const firstSeq = childProps.workflowActionRequest?.seq; fireEvent.click(screen.getByTestId("mock-handle-workflow-action")); await waitFor(() => expect(childProps.workflowActionRequest).toBeNull()); + + fireEvent.click(within(cta).getByRole("button", { name: "Next Action" })); + await waitFor(() => + expect(childProps.workflowActionRequest).toMatchObject({ + action: "open-lettering", + }), + ); + expect(childProps.workflowActionRequest?.seq).toBeGreaterThan(firstSeq ?? 0); }, 10000); it("passes generate-markdown through to PreviewPanel instead of dropping it at file selection", async () => { diff --git a/app/web/components/StoriesPage.tsx b/app/web/components/StoriesPage.tsx index 593cdf7..6615d2e 100644 --- a/app/web/components/StoriesPage.tsx +++ b/app/web/components/StoriesPage.tsx @@ -152,6 +152,7 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { const agentModeMap = useRef>(new Map()); const agentProviderMap = useRef>(new Map()); const knownStoriesRef = useRef>(new Set()); + const workflowActionSeqRef = useRef(0); const renameRef = useRef< | (( oldName: string, @@ -1069,10 +1070,11 @@ export function StoriesPage({ token, authFetch }: StoriesPageProps) { const story = selectedStory; if (!story) return; const queueWorkflowAction = (nextAction: CoachUiAction) => { - setWorkflowActionRequest((prev) => ({ + workflowActionSeqRef.current += 1; + setWorkflowActionRequest({ action: nextAction, - seq: (prev?.seq ?? 0) + 1, - })); + seq: workflowActionSeqRef.current, + }); }; switch (action) { case "view-progress": diff --git a/app/web/dist/assets/export-cut-m_bbvXgX.js b/app/web/dist/assets/export-cut-33MiJugN.js similarity index 98% rename from app/web/dist/assets/export-cut-m_bbvXgX.js rename to app/web/dist/assets/export-cut-33MiJugN.js index d10de7c..7622dfb 100644 --- a/app/web/dist/assets/export-cut-m_bbvXgX.js +++ b/app/web/dist/assets/export-cut-33MiJugN.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-OmkX9BzW.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-Ce_xoof_.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-OmkX9BzW.js b/app/web/dist/assets/index-Ce_xoof_.js similarity index 57% rename from app/web/dist/assets/index-OmkX9BzW.js rename to app/web/dist/assets/index-Ce_xoof_.js index 350202f..def67ae 100644 --- a/app/web/dist/assets/index-OmkX9BzW.js +++ b/app/web/dist/assets/index-Ce_xoof_.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 ib;function pC(){if(ib)return oo;ib=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 oo.Fragment=t,oo.jsx=i,oo.jsxs=i,oo}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={exports:{}},Qe={};/** + */var ib;function pC(){if(ib)return oo;ib=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 oo.Fragment=t,oo.jsx=i,oo.jsxs=i,oo}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={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 rb;function gC(){if(rb)return Qe;rb=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"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,M={};function E(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,X){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,X,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function O(){}O.prototype=E.prototype;function H(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}var A=H.prototype=new O;A.constructor=H,N(A,E.prototype),A.isPureReactComponent=!0;var W=Array.isArray;function R(){}var re={H:null,A:null,T:null,S:null},he=Object.prototype.hasOwnProperty;function be(D,X,C){var Z=C.ref;return{$$typeof:e,type:D,key:X,ref:Z!==void 0?Z:null,props:C}}function B(D,X){return be(D.type,X,D.props)}function se(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function F(D){var X={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(C){return X[C]})}var Y=/\/+/g;function V(D,X){return typeof D=="object"&&D!==null&&D.key!=null?F(""+D.key):X.toString(36)}function U(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(R,R):(D.status="pending",D.then(function(X){D.status==="pending"&&(D.status="fulfilled",D.value=X)},function(X){D.status==="pending"&&(D.status="rejected",D.reason=X)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function T(D,X,C,Z,ae){var oe=typeof D;(oe==="undefined"||oe==="boolean")&&(D=null);var K=!1;if(D===null)K=!0;else switch(oe){case"bigint":case"string":case"number":K=!0;break;case"object":switch(D.$$typeof){case e:case t:K=!0;break;case _:return K=D._init,T(K(D._payload),X,C,Z,ae)}}if(K)return ae=ae(D),K=Z===""?"."+V(D,0):Z,W(ae)?(C="",K!=null&&(C=K.replace(Y,"$&/")+"/"),T(ae,X,C,"",function(Me){return Me})):ae!=null&&(se(ae)&&(ae=B(ae,C+(ae.key==null||D&&D.key===ae.key?"":(""+ae.key).replace(Y,"$&/")+"/")+K)),X.push(ae)),1;K=0;var de=Z===""?".":Z+":";if(W(D))for(var ge=0;ge>>1,j=T[xe];if(0>>1;xea(C,q))Za(ae,C)?(T[xe]=ae,T[Z]=q,xe=Z):(T[xe]=C,T[X]=q,xe=X);else if(Za(ae,q))T[xe]=ae,T[Z]=q,xe=Z;else break e}}return z}function a(T,z){var q=T.sortIndex-z.sortIndex;return q!==0?q:T.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,H=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function W(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(W,z.startTime-T)}}var R=!1,re=-1,he=5,be=-1;function B(){return M?!0:!(e.unstable_now()-beT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&U(W,D.startTime-T),z=!1}}break e}finally{x=null,b=q,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof H=="function")F=function(){H(se)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,V=Y.port2;Y.port1.onmessage=se,F=function(){V.postMessage(null)}}else F=function(){E(se,0)};function U(T,z){re=E(function(){T(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(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=q,t(f,T),i(p)===null&&T===i(f)&&(N?(O(re),re=-1):N=!0,U(W,q-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,F()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var q=b;b=z;try{return T.apply(this,arguments)}finally{b=q}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},sn={};/** + */var ab;function _C(){return ab||(ab=1,(function(e){function t(T,z){var F=T.length;T.push(z);e:for(;0>>1,j=T[xe];if(0>>1;xea(C,F))Za(ae,C)?(T[xe]=ae,T[Z]=F,xe=Z):(T[xe]=C,T[X]=F,xe=X);else if(Za(ae,F))T[xe]=ae,T[Z]=F,xe=Z;else break e}}return z}function a(T,z){var F=T.sortIndex-z.sortIndex;return F!==0?F:T.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,$());else{var z=i(f);z!==null&&H(q,z.startTime-T)}}var R=!1,re=-1,ue=5,ye=-1;function B(){return M?!0:!(e.unstable_now()-yeT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&H(q,D.startTime-T),z=!1}}break e}finally{x=null,b=F,v=!1}z=void 0}}finally{z?$():R=!1}}}var $;if(typeof I=="function")$=function(){I(se)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,V=G.port2;G.port1.onmessage=se,$=function(){V.postMessage(null)}}else $=function(){E(se,0)};function H(T,z){re=E(function(){T(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(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=F,t(f,T),i(p)===null&&T===i(f)&&(N?(O(re),re=-1):N=!0,H(q,F-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,$()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var F=b;b=z;try{return T.apply(this,arguments)}finally{b=F}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},ln={};/** * @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 ob;function vC(){if(ob)return sn;ob=1;var e=$p();function t(p){var f="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(),Jd.exports=vC(),Jd.exports}/** + */var ob;function vC(){if(ob)return ln;ob=1;var e=$p();function t(p){var f="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(),Jd.exports=vC(),Jd.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 ub;function SC(){if(ub)return co;ub=1;var e=bC(),t=$p(),i=yC();function s(n){var r="https://react.dev/errors/"+n;if(1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function de(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function Me(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function Pe(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),ro._currentValue=q)}var Fe,Se;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",Se=-1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function he(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function De(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function ze(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),ro._currentValue=F)}var Fe,we;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",we=-1)":-1m||L[u]!==ee[m]){var ue=` -`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{Je=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function et(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return He("Activity");default:return""}}function jt(n){try{var r="",l=null;do r+=et(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`+Fe+n+we}var tt=!1;function st(n,r){if(!n||tt)return"";tt=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(r){var fe=function(){throw Error()};if(Object.defineProperty(fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(fe,[])}catch(le){var ie=le}Reflect.construct(n,[],fe)}else{try{fe.call()}catch(le){ie=le}n.call(fe.prototype)}}else{try{throw Error()}catch(le){ie=le}(fe=n())&&typeof fe.catch=="function"&&fe.catch(function(){})}}catch(le){if(le&&ie&&typeof le.stack=="string")return[le.stack,ie.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=u.DetermineComponentFrameRoot(),y=g[0],k=g[1];if(y&&k){var L=y.split(` +`),J=k.split(` +`);for(m=u=0;um||L[u]!==J[m]){var ce=` +`+L[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{tt=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function it(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return st(n.type,!1);case 11:return st(n.type.render,!1);case 1:return st(n.type,!0);case 31:return He("Activity");default:return""}}function Nt(n){try{var r="",l=null;do r+=it(n,l),l=n,n=n.return;while(n);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Oe=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,je=e.unstable_cancelCallback,Gt=e.unstable_shouldYield,yi=e.unstable_requestPaint,kt=e.unstable_now,Xe=e.unstable_getCurrentPriorityLevel,te=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Be=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Ke=e.unstable_IdlePriority,Yt=e.log,fi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Ht(n){if(typeof Yt=="function"&&fi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var nt=Math.clz32?Math.clz32:we,Xt=Math.log,$=Math.LN2;function we(n){return n>>>=0,n===0?32:31-(Xt(n)/$|0)|0}var Ee=256,Ae=262144,Ye=4194304;function Ue(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 ut(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(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 vt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(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 Bt(){var n=Ye;return Ye<<=1,(Ye&62914560)===0&&(Ye=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Vt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function rn(n,r,l,u,m,g){var y=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,L=n.expirationTimes,ee=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Sa=/[\n"\\]/g;function Oi(n){return n.replace(Sa,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function mi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ai(r)):n.value!==""+Ai(r)&&(n.value=""+Ai(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Vi(n,y,Ai(r)):l!=null?Vi(n,y,Ai(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=""+Ai(k):n.removeAttribute("name")}function gr(n,r,l,u,m,g,y,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)){Mn(n);return}l=l!=null?""+Ai(l):"",r=r!=null?""+Ai(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Mn(n)}function Vi(n,r,l){r==="number"&&mr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Ki(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"),hs=!1;if(lr)try{var ds={};Object.defineProperty(ds,"passive",{get:function(){hs=!0}}),window.addEventListener("test",ds,ds),window.removeEventListener("test",ds,ds)}catch{hs=!1}var ne=null,ke=null,Ne=null;function it(){if(Ne)return Ne;var n,r=ke,l=r.length,u,m="value"in ne?ne.value:ne.textContent,g=m.length;for(n=0;n=kl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ca=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(Ca)return n==="compositionend"||!eh&&Bm(n,r)?(n=it(),Ne=ke=ne=null,Ca=!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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=mr(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=mr(n.document)}return r}function nh(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 Y1=lr&&"documentMode"in document&&11>=document.documentMode,ka=null,rh=null,Tl=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||ka==null||ka!==mr(u)||(u=ka,"selectionStart"in u&&nh(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}),Tl&&jl(Tl,u)||(Tl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-nt(r)+m|l<lt?(_t=Ie,Ie=null):_t=Ie.sibling;var Nt=ie(G,Ie,J[lt],fe);if(Nt===null){Ie===null&&(Ie=_t);break}n&&Ie&&Nt.alternate===null&&r(G,Ie),I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt,Ie=_t}if(lt===J.length)return l(G,Ie),bt&&Hr(G,lt),qe;if(Ie===null){for(;ltlt?(_t=Ie,Ie=null):_t=Ie.sibling;var Bs=ie(G,Ie,Nt.value,fe);if(Bs===null){Ie===null&&(Ie=_t);break}n&&Ie&&Bs.alternate===null&&r(G,Ie),I=g(Bs,I,lt),Et===null?qe=Bs:Et.sibling=Bs,Et=Bs,Ie=_t}if(Nt.done)return l(G,Ie),bt&&Hr(G,lt),qe;if(Ie===null){for(;!Nt.done;lt++,Nt=J.next())Nt=pe(G,Nt.value,fe),Nt!==null&&(I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt);return bt&&Hr(G,lt),qe}for(Ie=u(Ie);!Nt.done;lt++,Nt=J.next())Nt=le(Ie,G,lt,Nt.value,fe),Nt!==null&&(n&&Nt.alternate!==null&&Ie.delete(Nt.key===null?lt:Nt.key),I=g(Nt,I,lt),Et===null?qe=Nt:Et.sibling=Nt,Et=Nt);return n&&Ie.forEach(function(fC){return r(G,fC)}),bt&&Hr(G,lt),qe}function Pt(G,I,J,fe){if(typeof J=="object"&&J!==null&&J.type===N&&J.key===null&&(J=J.props.children),typeof J=="object"&&J!==null){switch(J.$$typeof){case v:e:{for(var qe=J.key;I!==null;){if(I.key===qe){if(qe=J.type,qe===N){if(I.tag===7){l(G,I.sibling),fe=m(I,J.props.children),fe.return=G,G=fe;break e}}else if(I.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===he&&ia(qe)===I.type){l(G,I.sibling),fe=m(I,J.props),Ll(fe,J),fe.return=G,G=fe;break e}l(G,I);break}else r(G,I);I=I.sibling}J.type===N?(fe=Zs(J.props.children,G.mode,fe,J.key),fe.return=G,G=fe):(fe=rc(J.type,J.key,J.props,null,G.mode,fe),Ll(fe,J),fe.return=G,G=fe)}return y(G);case S:e:{for(qe=J.key;I!==null;){if(I.key===qe)if(I.tag===4&&I.stateNode.containerInfo===J.containerInfo&&I.stateNode.implementation===J.implementation){l(G,I.sibling),fe=m(I,J.children||[]),fe.return=G,G=fe;break e}else{l(G,I);break}else r(G,I);I=I.sibling}fe=dh(J,G.mode,fe),fe.return=G,G=fe}return y(G);case he:return J=ia(J),Pt(G,I,J,fe)}if(U(J))return ze(G,I,J,fe);if(F(J)){if(qe=F(J),typeof qe!="function")throw Error(s(150));return J=qe.call(J),Ge(G,I,J,fe)}if(typeof J.then=="function")return Pt(G,I,hc(J),fe);if(J.$$typeof===H)return Pt(G,I,lc(G,J),fe);dc(G,J)}return typeof J=="string"&&J!==""||typeof J=="number"||typeof J=="bigint"?(J=""+J,I!==null&&I.tag===6?(l(G,I.sibling),fe=m(I,J),fe.return=G,G=fe):(l(G,I),fe=hh(J,G.mode,fe),fe.return=G,G=fe),y(G)):l(G,I)}return function(G,I,J,fe){try{Bl=0;var qe=Pt(G,I,J,fe);return Oa=null,qe}catch(Ie){if(Ie===La||Ie===cc)throw Ie;var Et=Ln(29,Ie,null,G.mode);return Et.lanes=fe,Et.return=G,Et}finally{}}}var ra=gg(!0),xg=gg(!1),xs=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 _s(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function bs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ol(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,vn(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function zl(){if(Nh){var n=Ba;if(n!==null)throw n}}function Pl(n,r,l,u){Nh=!1;var m=n.updateQueue;xs=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,ee=L.next;L.next=null,y===null?g=ee:y.next=ee,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=ee:k.next=ee,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=ee=L=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(xt&ie)===ie:(u&ie)===ie){ie!==0&&ie===Ma&&(Nh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var ze=n,Ge=k;ie=r;var Pt=l;switch(Ge.tag){case 1:if(ze=Ge.payload,typeof ze=="function"){pe=ze.call(Pt,pe,ie);break e}pe=ze;break e;case 3:ze.flags=ze.flags&-65537|128;case 0:if(ze=Ge.payload,ie=typeof ze=="function"?ze.call(Pt,pe,ie):ze,ie==null)break e;pe=x({},pe,ie);break e;case 2:xs=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(ee=ue=le,L=pe):ue=ue.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=ee,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Cs|=y,n.lanes=y,n.memoizedState=pe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var L=m(),ee=T.S;if(ee!==null&&ee(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=iw(L,u);Ul(n,r,ue,Hn(n))}else Ul(n,r,u,Hn(n))}catch(pe){Ul(n,r,{then:function(){},status:"rejected",reason:pe},Hn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,q,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:q,baseState:q,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qr,lastRenderedState:q},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Ul(n,r.next.queue,{},Hn())}function Wh(){return Zi(ro)}function Jg(){return bi().memoizedState}function ex(){return bi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Hn();n=_s(l);var u=bs(r,n,l);u!==null&&(Nn(u,r,l),Ol(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Hn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(Nn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Hn();Ul(n,r,l,u)}function Ul(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Bn(k,y))return ic(n,r,m,0),qt===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return Nn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&Nn(r,n,2)}function Sc(n){var r=n.alternate;return n===st||r!==null&&r===st}function ix(n,r){Pa=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,vn(n,l)}}var $l={readContext:Zi,use:_c,useCallback:oi,useContext:oi,useEffect:oi,useImperativeHandle:oi,useLayoutEffect:oi,useInsertionEffect:oi,useMemo:oi,useReducer:oi,useRef:oi,useState:oi,useDebugValue:oi,useDeferredValue:oi,useTransition:oi,useSyncExternalStore:oi,useId:oi,useHostTransitionStatus:oi,useFormState:oi,useActionState:oi,useOptimistic:oi,useMemoCache:oi,useCacheRefresh:oi};$l.useEffectEvent=oi;var rx={readContext:Zi,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Zi,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Ht(!0);try{n()}finally{Ht(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Ht(!0);try{l(r)}finally{Ht(!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=uw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,st,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),qt===null)throw Error(s(349));(xt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Ha(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=qt.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-nt(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Zt]=r,g[Q]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Ji(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&&Gr(r)}}return Jt(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Gr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ra(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Xi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Zt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||ms(r,!0)}else n=$c(n).createTextNode(u),n[Zt]=r,r.stateNode=n}return Jt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ra(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Jt(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(zn(r),r):(zn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Jt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ra(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Jt(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(zn(r),r):(zn(r),null)}return zn(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),Nc(r,r.updateQueue),Jt(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),Jt(r),null;case 10:return $r(r.type),Jt(r),null;case 19:if(X(_i),u=r.memoizedState,u===null)return Jt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)ql(u,!1);else{if(ci!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,ql(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(_i,_i.current&1|2),bt&&Hr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&kt()>Dc&&(r.flags|=128,m=!0,ql(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),ql(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return Jt(r),null}else 2*kt()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,ql(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=kt(),n.sibling=null,l=_i.current,C(_i,m?l&1|2:l&1),bt&&Hr(r,u.treeForkCount),n):(Jt(r),null);case 22:case 23:return zn(r),Th(),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&&(Jt(r),r.subtreeFlags&6&&(r.flags|=8192)):Jt(r),l=r.updateQueue,l!==null&&Nc(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&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),$r(wi),Jt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return $r(wi),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Pe(r),null;case 31:if(r.memoizedState!==null){if(zn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(zn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(_i),null;case 4:return ge(),null;case 10:return $r(r.type),null;case 22:case 23:return zn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return $r(wi),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:$r(wi),ge();break;case 26:case 27:case 5:Pe(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&zn(r);break;case 13:zn(r);break;case 19:X(_i);break;case 10:$r(r.type);break;case 22:case 23:zn(r),Th(),n!==null&&X(ta);break;case 24:$r(wi)}}function Wl(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function Ss(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,ee=k;try{ee()}catch(ue){Mt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){Mt(r,r.return,ue)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Gl(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){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(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){Mt(n,r,m)}else l.current=null}function Rx(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){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[Q]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ts(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&Ts(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 cd(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=Gn));else if(u!==4&&(u===27&&Ts(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&Ts(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Ji(r,u,l),r[Zt]=n,r[Q]=l}catch(g){Mt(n,n.return,g)}}var Yr=!1,Ei=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,zi=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(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 y=0,k=-1,L=-1,ee=0,ue=0,pe=n,ie=null;t:for(;;){for(var le;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(le=pe.firstChild)!==null;)ie=pe,pe=le;for(;;){if(pe===n)break t;if(ie===l&&++ee===m&&(k=y),ie===g&&++ue===u&&(L=y),(le=pe.nextSibling)!==null)break;pe=ie,ie=pe.parentNode}pe=le}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,zi=r;zi!==null;)if(r=zi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,zi=n;else for(;zi!==null;){switch(r=zi,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"))),Ji(g,u,l),g[Zt]=n,Ze(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ge,Ge=y);var G=qm(k,Ge),I=qm(k,Pt);if(G&&I&&(le.rangeCount!==1||le.anchorNode!==G.node||le.anchorOffset!==G.offset||le.focusNode!==I.node||le.focusOffset!==I.offset)){var J=pe.createRange();J.setStart(G.node,G.offset),le.removeAllRanges(),Ge>Pt?(le.addRange(J),le.extend(I.node,I.offset)):(J.setEnd(I.node,I.offset),le.addRange(J))}}}}for(pe=[],le=k;le=le.parentNode;)le.nodeType===1&&pe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=Es,y=Qr;if(Ri=0,Wa=Es=null,Qr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Ql(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Vn(l,r),r=Xh(n.stateNode,r,2),n=bs(n,r,2),n!==null&&(Vt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ks===null||!ks.has(u))){n=Vn(l,n),l=dx(2),u=bs(r,l,2),u!==null&&(fx(l,u,r,n),Vt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,qt===n&&(xt&l)===l&&(ci===4||ci===3&&(xt&62914560)===xt&&300>kt()-Rc?(Tt&2)===0&&Ga(n,0):pd|=l,qa===xt&&(qa=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Vt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Va=null,Sd=!1,Ic=!1,wd=!1,js=0;function Cr(n){n!==Va&&n.next===null&&(Va===null?Pc=Va=n:Va=Va.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Ql(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-nt(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=xt,g=ut(u,u===qt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||vt(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;js!==0&&Iw()&&(n=js);for(var r=kt(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Va=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Ri!==0&&Ri!==5||Ql(n),js!==0&&(js=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&C_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function O_(n,r,l){var u=Ka;if(u&&typeof r=="string"&&r){var m=Oi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Ji(r,"link",n),Ze(r),u.head.appendChild(r)))}}function Vw(n){Jr.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){Jr.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){Jr.L(n,r,l);var u=Ka;if(u&&n&&r){var m='link[rel="preload"][as="'+Oi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Oi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Oi(l.imageSizes)+'"]')):m+='[href="'+Oi(n)+'"]';var g=m;switch(r){case"style":g=Xa(n);break;case"script":g=Za(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(io(g))||r==="script"&&u.querySelector(no(g))||(r=u.createElement("link"),Ji(r,"link",n),Ze(r),u.head.appendChild(r)))}}function Zw(n,r){Jr.m(n,r);var l=Ka;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Oi(u)+'"][href="'+Oi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Za(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(no(g)))return}u=l.createElement("link"),Ji(u,"link",n),Ze(u),l.head.appendChild(u)}}}function Qw(n,r,l){Jr.S(n,r,l);var u=Ka;if(u&&n){var m=Ct(u).hoistableStyles,g=Xa(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(io(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Id(n,l);var L=y=u.createElement("link");Ze(L),Ji(L,"link",n),L._p=new Promise(function(ee,ue){L.onload=ee,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){Jr.X(n,r);var l=Ka;if(l&&n){var u=Ct(l).hoistableScripts,m=Za(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Ze(g),Ji(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){Jr.M(n,r);var l=Ka;if(l&&n){var u=Ct(l).hoistableScripts,m=Za(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Ze(g),Ji(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(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=Xa(l.href),l=Ct(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=Xa(l.href);var g=Ct(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(io(n)))&&!g._p&&(y.instance=g,y.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||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Za(l),l=Ct(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 Xa(n){return'href="'+Oi(n)+'"'}function io(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),Ji(r,"link",l),Ze(r),n.head.appendChild(r))}function Za(n){return'[src="'+Oi(n)+'"]'}function no(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Oi(l.href)+'"]');if(u)return r.instance=u,Ze(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"),Ze(u),Ji(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Xa(l.href);var g=n.querySelector(io(m));if(g)return r.state.loading|=4,r.instance=g,Ze(g),g;u=P_(l),(m=er.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Ze(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ji(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Za(l.src),(m=n.querySelector(no(g)))?(r.instance=m,Ze(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Ze(m),Ji(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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=Xa(u.href),g=r.querySelector(io(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Ze(g);return}g=r.ownerDocument||r,u=P_(u),(m=er.get(m))&&Id(u,m),g=g.createElement("link"),Ze(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Ji(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,O)=>fetch(E,{...O,headers:{...O==null?void 0:O.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),O=await E.json();if(!E.ok)throw new Error(O.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const O=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),H=await O.json();if(!O.ok)throw new Error(H.error||"Wallet switch failed");b()}catch(O){_(O instanceof Error?O.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[O,H]=w.useState(""),[A,W]=w.useState(!1),[R,re]=w.useState(null),[he,be]=w.useState(""),[B,se]=w.useState(null),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,z]=w.useState(null),[q,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){re("Agent name is required");return}if(!M.trim()){re("Description is required");return}W(!0),re(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...O.trim()&&{genre:O}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){re(ae instanceof Error?ae.message:"Registration failed")}W(!1)},X=async()=>{if(!he.trim()||!/^0x[a-fA-F0-9]{40}$/.test(he)){U("Enter a valid wallet address (0x...)");return}Y(!0),U(null),se(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:he})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");se(oe)}catch(ae){U(ae instanceof Error?ae.message:"Failed to generate binding code")}Y(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!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 ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:O,onChange:ae=>H(ae.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.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:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(q==null?void 0:q.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(q==null?void 0:q.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:q!=null&&q.codex.installed?q.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(q)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.checkedAt?new Date(q.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:he,onChange:ae=>be(ae.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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:F||!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:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.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"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const W=await e("/api/stories");if(W.ok){const R=await W.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const W=await e("/api/stories/archived");if(W.ok){const R=await W.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async W=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:W})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const W=setInterval(S,5e3);return()=>clearInterval(W)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(W=>new Set(W).add(t))},[t]);const E=W=>{x(R=>{const re=new Set(R);return re.has(W)?re.delete(W):re.add(W),re})},O=W=>{var re;const R=W.map(he=>{var be;return{file:he.file,num:(be=he.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(he=>he.num!=null).sort((he,be)=>parseInt(be.num)-parseInt(he.num));return R.length>0?R[0].file:W.some(he=>he.file==="genesis.md")?"genesis.md":W.some(he=>he.file==="structure.md")?"structure.md":((re=W[0])==null?void 0:re.file)??null},H=W=>{if(E(W.name),W.contentType==="cartoon")s(W.name,"");else{const R=O(W.files);R&&s(W.name,R)}},A=W=>{const R=re=>{if(re==="structure.md")return 0;if(re==="genesis.md")return 1;const he=re.match(/^plot-(\d+)\.md$/);return he?2+parseInt(he[1]):100};return[...W].sort((re,he)=>R(re.file)-R(he.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(W=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:W.name,children:W.title||W.name}),d.jsx("button",{onClick:()=>M(W.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},W.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(W=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(W,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===W?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},W)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(W=>W.name!=="_example").map(W=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>H(W),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(W.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:W.name,children:W.title||W.name}),W.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[W.publishedCount,"/",W.files.length]})]}),_.has(W.name)&&d.jsx("div",{className:"pl-4",children:A(W.files).map(R=>{const re=t===W.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(W.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${re?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},W.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var Be=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,qt=e.unstable_shouldYield,yi=e.unstable_requestPaint,Ct=e.unstable_now,Je=e.unstable_getCurrentPriorityLevel,ee=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Me=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Xe=e.unstable_IdlePriority,Wt=e.log,pi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Gt(n){if(typeof Wt=="function"&&pi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var ot=Math.clz32?Math.clz32:Ce,Ht=Math.log,U=Math.LN2;function Ce(n){return n>>>=0,n===0?32:31-(Ht(n)/U|0)|0}var Ae=256,Ne=262144,Ge=4194304;function Ue(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(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 _t(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(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 Bt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Yt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function an(n,r,l,u,m,g){var y=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,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var xl=/[\n"\\]/g;function Si(n){return n.replace(xl,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function wi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Di(r)):n.value!==""+Di(r)&&(n.value=""+Di(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Xi(n,y,Di(r)):l!=null?Xi(n,y,Di(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=""+Di(k):n.removeAttribute("name")}function Bn(n,r,l,u,m,g,y,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)){ei(n);return}l=l!=null?""+Di(l):"",r=r!=null?""+Di(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),ei(n)}function Xi(n,r,l){r==="number"&&Lr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Zi(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"),ds=!1;if(cr)try{var fs={};Object.defineProperty(fs,"passive",{get:function(){ds=!0}}),window.addEventListener("test",fs,fs),window.removeEventListener("test",fs,fs)}catch{ds=!1}var ne=null,Ee=null,je=null;function nt(){if(je)return je;var n,r=Ee,l=r.length,u,m="value"in ne?ne.value:ne.textContent,g=m.length;for(n=0;n=kl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var wa=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(wa)return n==="compositionend"||!eh&&Bm(n,r)?(n=nt(),je=Ee=ne=null,wa=!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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=Lr(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=Lr(n.document)}return r}function nh(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 Y1=cr&&"documentMode"in document&&11>=document.documentMode,Ca=null,rh=null,Tl=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||Ca==null||Ca!==Lr(u)||(u=Ca,"selectionStart"in u&&nh(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}),Tl&&jl(Tl,u)||(Tl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-ot(r)+m|l<at?(xt=Ie,Ie=null):xt=Ie.sibling;var Et=ie(W,Ie,Q[at],de);if(Et===null){Ie===null&&(Ie=xt);break}n&&Ie&&Et.alternate===null&&r(W,Ie),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et,Ie=xt}if(at===Q.length)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;atat?(xt=Ie,Ie=null):xt=Ie.sibling;var Ls=ie(W,Ie,Et.value,de);if(Ls===null){Ie===null&&(Ie=xt);break}n&&Ie&&Ls.alternate===null&&r(W,Ie),P=g(Ls,P,at),kt===null?We=Ls:kt.sibling=Ls,kt=Ls,Ie=xt}if(Et.done)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;!Et.done;at++,Et=Q.next())Et=fe(W,Et.value,de),Et!==null&&(P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return bt&&Ur(W,at),We}for(Ie=u(Ie);!Et.done;at++,Et=Q.next())Et=le(Ie,W,at,Et.value,de),Et!==null&&(n&&Et.alternate!==null&&Ie.delete(Et.key===null?at:Et.key),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return n&&Ie.forEach(function(fC){return r(W,fC)}),bt&&Ur(W,at),We}function Pt(W,P,Q,de){if(typeof Q=="object"&&Q!==null&&Q.type===N&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case v:e:{for(var We=Q.key;P!==null;){if(P.key===We){if(We=Q.type,We===N){if(P.tag===7){l(W,P.sibling),de=m(P,Q.props.children),de.return=W,W=de;break e}}else if(P.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===ue&&ia(We)===P.type){l(W,P.sibling),de=m(P,Q.props),Ll(de,Q),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Q.type===N?(de=Zs(Q.props.children,W.mode,de,Q.key),de.return=W,W=de):(de=rc(Q.type,Q.key,Q.props,null,W.mode,de),Ll(de,Q),de.return=W,W=de)}return y(W);case S:e:{for(We=Q.key;P!==null;){if(P.key===We)if(P.tag===4&&P.stateNode.containerInfo===Q.containerInfo&&P.stateNode.implementation===Q.implementation){l(W,P.sibling),de=m(P,Q.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Q,W.mode,de),de.return=W,W=de}return y(W);case ue:return Q=ia(Q),Pt(W,P,Q,de)}if(H(Q))return Le(W,P,Q,de);if($(Q)){if(We=$(Q),typeof We!="function")throw Error(s(150));return Q=We.call(Q),Ve(W,P,Q,de)}if(typeof Q.then=="function")return Pt(W,P,hc(Q),de);if(Q.$$typeof===I)return Pt(W,P,lc(W,Q),de);dc(W,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Q),de.return=W,W=de):(l(W,P),de=hh(Q,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Q,de){try{Bl=0;var We=Pt(W,P,Q,de);return La=null,We}catch(Ie){if(Ie===Ba||Ie===cc)throw Ie;var kt=On(29,Ie,null,W.mode);return kt.lanes=de,kt.return=W,kt}finally{}}}var ra=gg(!0),xg=gg(!1),_s=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 bs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function vs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ol(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,An(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function zl(){if(Nh){var n=Ma;if(n!==null)throw n}}function Pl(n,r,l,u){Nh=!1;var m=n.updateQueue;_s=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==y&&(k===null?ce.firstBaseUpdate=J:k.next=J,ce.lastBaseUpdate=L))}if(g!==null){var fe=m.baseState;y=0,ce=J=L=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(gt&ie)===ie:(u&ie)===ie){ie!==0&&ie===Da&&(Nh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Le=n,Ve=k;ie=r;var Pt=l;switch(Ve.tag){case 1:if(Le=Ve.payload,typeof Le=="function"){fe=Le.call(Pt,fe,ie);break e}fe=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ve.payload,ie=typeof Le=="function"?Le.call(Pt,fe,ie):Le,ie==null)break e;fe=x({},fe,ie);break e;case 2:_s=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(J=ce=le,L=fe):ce=ce.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ce===null&&(L=fe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),ks|=y,n.lanes=y,n.memoizedState=fe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var L=m(),J=T.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ce=iw(L,u);Ul(n,r,ce,Un(n))}else Ul(n,r,u,Un(n))}catch(fe){Ul(n,r,{then:function(){},status:"rejected",reason:fe},Un())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,F,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:F},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Ul(n,r.next.queue,{},Un())}function Wh(){return Ji(ro)}function Jg(){return bi().memoizedState}function ex(){return bi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Un();n=bs(l);var u=vs(r,n,l);u!==null&&(kn(u,r,l),Ol(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Un();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(kn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Un();Ul(n,r,l,u)}function Ul(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Ln(k,y))return ic(n,r,m,0),$t===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return kn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&kn(r,n,2)}function Sc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function ix(n,r){za=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,An(n,l)}}var $l={readContext:Ji,use:_c,useCallback:ci,useContext:ci,useEffect:ci,useImperativeHandle:ci,useLayoutEffect:ci,useInsertionEffect:ci,useMemo:ci,useReducer:ci,useRef:ci,useState:ci,useDebugValue:ci,useDeferredValue:ci,useTransition:ci,useSyncExternalStore:ci,useId:ci,useHostTransitionStatus:ci,useFormState:ci,useActionState:ci,useOptimistic:ci,useMemoCache:ci,useCacheRefresh:ci};$l.useEffectEvent=ci;var rx={readContext:Ji,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Gt(!0);try{n()}finally{Gt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Gt(!0);try{l(r)}finally{Gt(!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=uw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,rt,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),$t===null)throw Error(s(349));(gt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Ia(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=$t.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-ot(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Qt]=r,g[te]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(tn(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&&Yr(r)}}return ii(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Yr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Aa(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Qt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||gs(r,!0)}else n=$c(n).createTextNode(u),n[Qt]=r,r.stateNode=n}return ii(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Aa(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[Qt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Pn(r),r):(Pn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return ii(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Aa(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[Qt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Pn(r),r):(Pn(r),null)}return Pn(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),Nc(r,r.updateQueue),ii(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),ii(r),null;case 10:return Fr(r.type),ii(r),null;case 19:if(X(_i),u=r.memoizedState,u===null)return ii(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)ql(u,!1);else{if(ui!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,ql(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(_i,_i.current&1|2),bt&&Ur(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Dc&&(r.flags|=128,m=!0,ql(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),ql(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return ii(r),null}else 2*Ct()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,ql(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=Ct(),n.sibling=null,l=_i.current,C(_i,m?l&1|2:l&1),bt&&Ur(r,u.treeForkCount),n):(ii(r),null);case 22:case 23:return Pn(r),Th(),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&&(ii(r),r.subtreeFlags&6&&(r.flags|=8192)):ii(r),l=r.updateQueue,l!==null&&Nc(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&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Fr(Ci),ii(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Fr(Ci),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return ze(r),null;case 31:if(r.memoizedState!==null){if(Pn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Pn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(_i),null;case 4:return ge(),null;case 10:return Fr(r.type),null;case 22:case 23:return Pn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Fr(Ci),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:Fr(Ci),ge();break;case 26:case 27:case 5:ze(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&Pn(r);break;case 13:Pn(r);break;case 19:X(_i);break;case 10:Fr(r.type);break;case 22:case 23:Pn(r),Th(),n!==null&&X(ta);break;case 24:Fr(Ci)}}function Wl(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function ws(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ce){Mt(m,L,ce)}}}u=u.next}while(u!==g)}}catch(ce){Mt(r,r.return,ce)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Gl(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){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(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){Mt(n,r,m)}else l.current=null}function Rx(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){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[te]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&As(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&As(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 cd(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=Yn));else if(u!==4&&(u===27&&As(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&As(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);tn(r,u,l),r[Qt]=n,r[te]=l}catch(g){Mt(n,n.return,g)}}var Vr=!1,Ni=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Hi=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(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 y=0,k=-1,L=-1,J=0,ce=0,fe=n,ie=null;t:for(;;){for(var le;fe!==l||m!==0&&fe.nodeType!==3||(k=y+m),fe!==g||u!==0&&fe.nodeType!==3||(L=y+u),fe.nodeType===3&&(y+=fe.nodeValue.length),(le=fe.firstChild)!==null;)ie=fe,fe=le;for(;;){if(fe===n)break t;if(ie===l&&++J===m&&(k=y),ie===g&&++ce===u&&(L=y),(le=fe.nextSibling)!==null)break;fe=ie,ie=fe.parentNode}fe=le}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,Hi=r;Hi!==null;)if(r=Hi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Hi=n;else for(;Hi!==null;){switch(r=Hi,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"))),tn(g,u,l),g[Qt]=n,Qe(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Pt);if(W&&P&&(le.rangeCount!==1||le.anchorNode!==W.node||le.anchorOffset!==W.offset||le.focusNode!==P.node||le.focusOffset!==P.offset)){var Q=fe.createRange();Q.setStart(W.node,W.offset),le.removeAllRanges(),Ve>Pt?(le.addRange(Q),le.extend(P.node,P.offset)):(Q.setEnd(P.node,P.offset),le.addRange(Q))}}}}for(fe=[],le=k;le=le.parentNode;)le.nodeType===1&&fe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=Ns,y=Jr;if(Mi=0,qa=Ns=null,Jr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Ql(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Kn(l,r),r=Xh(n.stateNode,r,2),n=vs(n,r,2),n!==null&&(Yt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(Es===null||!Es.has(u))){n=Kn(l,n),l=dx(2),u=vs(r,l,2),u!==null&&(fx(l,u,r,n),Yt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,$t===n&&(gt&l)===l&&(ui===4||ui===3&&(gt&62914560)===gt&&300>Ct()-Rc?(Tt&2)===0&&Wa(n,0):pd|=l,Fa===gt&&(Fa=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Yt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Ya=null,Sd=!1,Ic=!1,wd=!1,Ts=0;function Cr(n){n!==Ya&&n.next===null&&(Ya===null?Pc=Ya=n:Ya=Ya.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Ql(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-ot(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=gt,g=dt(u,u===$t?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||_t(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;Ts!==0&&Iw()&&(n=Ts);for(var r=Ct(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Ya=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Mi!==0&&Mi!==5||Ql(n),Ts!==0&&(Ts=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ce=L.transferSize,fe=L.initiatorType;ce&&C_(fe)&&(L=L.responseEnd,y+=ce*(L"u"?null:document;function O_(n,r,l){var u=Va;if(u&&typeof r=="string"&&r){var m=Si(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Vw(n){es.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){es.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){es.L(n,r,l);var u=Va;if(u&&n&&r){var m='link[rel="preload"][as="'+Si(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Si(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Si(l.imageSizes)+'"]')):m+='[href="'+Si(n)+'"]';var g=m;switch(r){case"style":g=Ka(n);break;case"script":g=Xa(n)}tr.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),tr.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(io(g))||r==="script"&&u.querySelector(no(g))||(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Zw(n,r){es.m(n,r);var l=Va;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Si(u)+'"][href="'+Si(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Xa(n)}if(!tr.has(g)&&(n=x({rel:"modulepreload",href:n},r),tr.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(no(g)))return}u=l.createElement("link"),tn(u,"link",n),Qe(u),l.head.appendChild(u)}}}function Qw(n,r,l){es.S(n,r,l);var u=Va;if(u&&n){var m=Ze(u).hoistableStyles,g=Ka(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(io(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=tr.get(g))&&Id(n,l);var L=y=u.createElement("link");Qe(L),tn(L,"link",n),L._p=new Promise(function(J,ce){L.onload=J,L.onerror=ce}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){es.X(n,r);var l=Va;if(l&&n){var u=Ze(l).hoistableScripts,m=Xa(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0},r),(r=tr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){es.M(n,r);var l=Va;if(l&&n){var u=Ze(l).hoistableScripts,m=Xa(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=tr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(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=Ka(l.href),l=Ze(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=Ka(l.href);var g=Ze(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(io(n)))&&!g._p&&(y.instance=g,y.state.loading=5),tr.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},tr.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Xa(l),l=Ze(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 Ka(n){return'href="'+Si(n)+'"'}function io(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),tn(r,"link",l),Qe(r),n.head.appendChild(r))}function Xa(n){return'[src="'+Si(n)+'"]'}function no(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Si(l.href)+'"]');if(u)return r.instance=u,Qe(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"),Qe(u),tn(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ka(l.href);var g=n.querySelector(io(m));if(g)return r.state.loading|=4,r.instance=g,Qe(g),g;u=P_(l),(m=tr.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Qe(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),tn(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Xa(l.src),(m=n.querySelector(no(g)))?(r.instance=m,Qe(m),m):(u=l,(m=tr.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Qe(m),tn(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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=Ka(u.href),g=r.querySelector(io(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Qe(g);return}g=r.ownerDocument||r,u=P_(u),(m=tr.get(m))&&Id(u,m),g=g.createElement("link"),Qe(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),tn(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,O)=>fetch(E,{...O,headers:{...O==null?void 0:O.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),O=await E.json();if(!E.ok)throw new Error(O.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const O=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await O.json();if(!O.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(O){_(O instanceof Error?O.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[O,I]=w.useState(""),[A,q]=w.useState(!1),[R,re]=w.useState(null),[ue,ye]=w.useState(""),[B,se]=w.useState(null),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(null),[F,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){re("Agent name is required");return}if(!M.trim()){re("Description is required");return}q(!0),re(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...O.trim()&&{genre:O}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){re(ae instanceof Error?ae.message:"Registration failed")}q(!1)},X=async()=>{if(!ue.trim()||!/^0x[a-fA-F0-9]{40}$/.test(ue)){H("Enter a valid wallet address (0x...)");return}G(!0),H(null),se(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:ue})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");se(oe)}catch(ae){H(ae instanceof Error?ae.message:"Failed to generate binding code")}G(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!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 ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:O,onChange:ae=>I(ae.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.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:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(F==null?void 0:F.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(F==null?void 0:F.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:F!=null&&F.codex.installed?F.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(F)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.checkedAt?new Date(F.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:ue,onChange:ae=>ye(ae.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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:$||!ue.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:$?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.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"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const re=new Set(R);return re.has(q)?re.delete(q):re.add(q),re})},O=q=>{var re;const R=q.map(ue=>{var ye;return{file:ue.file,num:(ye=ue.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(ue=>ue.num!=null).sort((ue,ye)=>parseInt(ye.num)-parseInt(ue.num));return R.length>0?R[0].file:q.some(ue=>ue.file==="genesis.md")?"genesis.md":q.some(ue=>ue.file==="structure.md")?"structure.md":((re=q[0])==null?void 0:re.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=O(q.files);R&&s(q.name,R)}},A=q=>{const R=re=>{if(re==="structure.md")return 0;if(re==="genesis.md")return 1;const ue=re.match(/^plot-(\d+)\.md$/);return ue?2+parseInt(ue[1]):100};return[...q].sort((re,ue)=>R(re.file)-R(ue.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:A(q.files).map(R=>{const re=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${re?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -57,21 +57,21 @@ Error generating stack: `+u.message+` * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},di=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Is(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",Us=" ",Uo=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 zy;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}},Nu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Iy extends Uo{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Is(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()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Gi(e){if(tf.has(e))return tf.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");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Gi("BufferService"),Hy=Gi("CoreMouseService"),va=Gi("CoreService"),qC=Gi("CharsetService"),qp=Gi("InstantiationService"),Uy=Gi("LogService"),bn=Gi("OptionsService"),$y=Gi("OscLinkService"),WC=Gi("UnicodeService"),$o=Gi("DecorationService"),qf=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,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=di([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},fi=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Hs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",$s=" ",Uo=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 zy;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}},Nu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},ar=class Iy extends Uo{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Hs(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()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Ki(e){if(tf.has(e))return tf.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");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Ki("BufferService"),Hy=Ki("CoreMouseService"),va=Ki("CoreService"),qC=Ki("CharsetService"),qp=Ki("InstantiationService"),Uy=Ki("LogService"),bn=Ki("OptionsService"),$y=Ki("OscLinkService"),WC=Ki("UnicodeService"),$o=Ki("DecorationService"),qf=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 ar,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=fi([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(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 Hu=Gi("CharSizeService"),ss=Gi("CoreBrowserService"),Wp=Gi("MouseService"),as=Gi("RenderService"),YC=Gi("SelectionService"),Fy=Gi("CharacterJoinerService"),pl=Gi("ThemeService"),qy=Gi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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 Hu=Ki("CharSizeService"),as=Ki("CoreBrowserService"),Wp=Ki("MouseService"),ls=Ki("RenderService"),YC=Ki("SelectionService"),Fy=Ki("CharacterJoinerService"),fl=Ki("ThemeService"),qy=Ki("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function Un(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let W=A.length-1;W>=0;W--)yield A[W]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,W){let R=0;for(let re of A)if(W(re,R++))return!0;return!1}e.some=_;function x(A,W){for(let R of A)if(W(R))return R}e.find=x;function*b(A,W){for(let R of A)W(R)&&(yield R)}e.filter=b;function*v(A,W){let R=0;for(let re of A)yield W(re,R++)}e.map=v;function*S(A,W){let R=0;for(let re of A)yield*W(re,R++)}e.flatMap=S;function*N(...A){for(let W of A)yield*W}e.concat=N;function M(A,W,R){let re=R;for(let he of A)re=W(re,he);return re}e.reduce=M;function*E(A,W,R=A.length){for(W<0&&(W+=A.length),R<0?R+=A.length:R>A.length&&(R=A.length);W1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function tk(...e){return ni(()=>xa(e))}function ni(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{xa(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var $s=Yy,dt=class{constructor(){this._store=new $s,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 hl=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}},rs=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var ai=Vf,xb=class{constructor(){this._first=ai.Undefined,this._last=ai.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ai.Undefined}clear(){let e=this._first;for(;e!==ai.Undefined;){let t=e.next;e.prev=ai.Undefined,e.next=ai.Undefined,e=t}this._first=ai.Undefined,this._last=ai.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ai(e);if(this._first===ai.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!==ai.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ai.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ai.Undefined&&e.next!==ai.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ai.Undefined&&e.next===ai.Undefined?(this._first=ai.Undefined,this._last=ai.Undefined):e.next===ai.Undefined?(this._last=this._last.prev,this._last.next=ai.Undefined):e.prev===ai.Undefined&&(this._first=this._first.next,this._first.prev=ai.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ai.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},nn;(e=>{e.None=()=>dt.None;function t(F,Y){return x(F,()=>{},0,void 0,!0,void 0,Y)}e.defer=t;function i(F){return(Y,V=null,U)=>{let T=!1,z;return z=F(q=>{if(!T)return z?z.dispose():T=!0,Y.call(V,q)},null,U),T&&z.dispose(),z}}e.once=i;function s(F,Y,V){return f((U,T=null,z)=>F(q=>U.call(T,Y(q)),null,z),V)}e.map=s;function a(F,Y,V){return f((U,T=null,z)=>F(q=>{Y(q),U.call(T,q)},null,z),V)}e.forEach=a;function o(F,Y,V){return f((U,T=null,z)=>F(q=>Y(q)&&U.call(T,q),null,z),V)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(Y,V=null,U)=>{let T=tk(...F.map(z=>z(q=>Y.call(V,q))));return _(T,U)}}e.any=h;function p(F,Y,V,U){let T=V;return s(F,z=>(T=Y(T,z),T),U)}e.reduce=p;function f(F,Y){let V,U={onWillAddFirstListener(){V=F(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new Ce(U);return Y==null||Y.add(T),T.event}function _(F,Y){return Y instanceof Array?Y.push(F):Y&&Y.add(F),F}function x(F,Y,V=100,U=!1,T=!1,z,q){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=F(oe=>{X++,j=Y(j,oe),U&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!U||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new Ce(Z);return q==null||q.add(ae),ae.event}e.debounce=x;function b(F,Y=0,V){return e.debounce(F,(U,T)=>U?(U.push(T),U):[T],Y,void 0,!0,void 0,V)}e.accumulate=b;function v(F,Y=(U,T)=>U===T,V){let U=!0,T;return o(F,z=>{let q=U||!Y(z,T);return U=!1,T=z,q},V)}e.latch=v;function S(F,Y,V){return[e.filter(F,Y,V),e.filter(F,U=>!Y(U),V)]}e.split=S;function N(F,Y=!1,V=[],U){let T=V.slice(),z=F(j=>{T?T.push(j):xe.fire(j)});U&&U.add(z);let q=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new Ce({onWillAddFirstListener(){z||(z=F(j=>xe.fire(j)),U&&U.add(z))},onDidAddFirstListener(){T&&(Y?setTimeout(q):q())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(xe),xe.event}e.buffer=N;function M(F,Y){return(V,U,T)=>{let z=Y(new O);return F(function(q){let xe=z.evaluate(q);xe!==E&&V.call(U,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(Y){return this.steps.push(Y),this}forEach(Y){return this.steps.push(V=>(Y(V),V)),this}filter(Y){return this.steps.push(V=>Y(V)?V:E),this}reduce(Y,V){let U=V;return this.steps.push(T=>(U=Y(U,T),U)),this}latch(Y=(V,U)=>V===U){let V=!0,U;return this.steps.push(T=>{let z=V||!Y(T,U);return V=!1,U=T,z?T:E}),this}evaluate(Y){for(let V of this.steps)if(Y=V(Y),Y===E)break;return Y}}function H(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.on(Y,U),z=()=>F.removeListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:z});return q.event}e.fromNodeEventEmitter=H;function A(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.addEventListener(Y,U),z=()=>F.removeEventListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:z});return q.event}e.fromDOMEventEmitter=A;function W(F){return new Promise(Y=>i(F)(Y))}e.toPromise=W;function R(F){let Y=new Ce;return F.then(V=>{Y.fire(V)},()=>{Y.fire(void 0)}).finally(()=>{Y.dispose()}),Y.event}e.fromPromise=R;function re(F,Y){return F(V=>Y.fire(V))}e.forward=re;function he(F,Y,V){return Y(V),F(U=>Y(U))}e.runAndSubscribe=he;class be{constructor(Y,V){this._observable=Y,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{Y.addObserver(this)},onDidRemoveLastListener:()=>{Y.removeObserver(this)}};this.emitter=new Ce(U),V&&V.add(this.emitter)}beginUpdate(Y){this._counter++}handlePossibleChange(Y){}handleChange(Y,V){this._hasChanged=!0}endUpdate(Y){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function B(F,Y){return new be(F,Y).emitter.event}e.fromObservable=B;function se(F){return(Y,V,U)=>{let T=0,z=!1,q={beginUpdate(){T++},endUpdate(){T--,T===0&&(F.reportChanges(),z&&(z=!1,Y.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver(q),F.reportChanges();let xe={dispose(){F.removeObserver(q)}};return U instanceof $s?U.add(xe):Array.isArray(U)&&U.push(xe),xe}}e.fromObservableLight=se})(nn||(nn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function $n(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let q=A.length-1;q>=0;q--)yield A[q]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,q){let R=0;for(let re of A)if(q(re,R++))return!0;return!1}e.some=_;function x(A,q){for(let R of A)if(q(R))return R}e.find=x;function*b(A,q){for(let R of A)q(R)&&(yield R)}e.filter=b;function*v(A,q){let R=0;for(let re of A)yield q(re,R++)}e.map=v;function*S(A,q){let R=0;for(let re of A)yield*q(re,R++)}e.flatMap=S;function*N(...A){for(let q of A)yield*q}e.concat=N;function M(A,q,R){let re=R;for(let ue of A)re=q(re,ue);return re}e.reduce=M;function*E(A,q,R=A.length){for(q<0&&(q+=A.length),R<0?R+=A.length:R>A.length&&(R=A.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 tk(...e){return si(()=>xa(e))}function si(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{xa(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var Fs=Yy,ht=class{constructor(){this._store=new Fs,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)}};ht.None=Object.freeze({dispose(){}});var ul=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}},ss=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var li=Vf,xb=class{constructor(){this._first=li.Undefined,this._last=li.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===li.Undefined}clear(){let e=this._first;for(;e!==li.Undefined;){let t=e.next;e.prev=li.Undefined,e.next=li.Undefined,e=t}this._first=li.Undefined,this._last=li.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new li(e);if(this._first===li.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!==li.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==li.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==li.Undefined&&e.next!==li.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===li.Undefined&&e.next===li.Undefined?(this._first=li.Undefined,this._last=li.Undefined):e.next===li.Undefined?(this._last=this._last.prev,this._last.next=li.Undefined):e.prev===li.Undefined&&(this._first=this._first.next,this._first.prev=li.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==li.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},sn;(e=>{e.None=()=>ht.None;function t($,G){return x($,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i($){return(G,V=null,H)=>{let T=!1,z;return z=$(F=>{if(!T)return z?z.dispose():T=!0,G.call(V,F)},null,H),T&&z.dispose(),z}}e.once=i;function s($,G,V){return f((H,T=null,z)=>$(F=>H.call(T,G(F)),null,z),V)}e.map=s;function a($,G,V){return f((H,T=null,z)=>$(F=>{G(F),H.call(T,F)},null,z),V)}e.forEach=a;function o($,G,V){return f((H,T=null,z)=>$(F=>G(F)&&H.call(T,F),null,z),V)}e.filter=o;function c($){return $}e.signal=c;function h(...$){return(G,V=null,H)=>{let T=tk(...$.map(z=>z(F=>G.call(V,F))));return _(T,H)}}e.any=h;function p($,G,V,H){let T=V;return s($,z=>(T=G(T,z),T),H)}e.reduce=p;function f($,G){let V,H={onWillAddFirstListener(){V=$(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new ke(H);return G==null||G.add(T),T.event}function _($,G){return G instanceof Array?G.push($):G&&G.add($),$}function x($,G,V=100,H=!1,T=!1,z,F){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=$(oe=>{X++,j=G(j,oe),H&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!H||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new ke(Z);return F==null||F.add(ae),ae.event}e.debounce=x;function b($,G=0,V){return e.debounce($,(H,T)=>H?(H.push(T),H):[T],G,void 0,!0,void 0,V)}e.accumulate=b;function v($,G=(H,T)=>H===T,V){let H=!0,T;return o($,z=>{let F=H||!G(z,T);return H=!1,T=z,F},V)}e.latch=v;function S($,G,V){return[e.filter($,G,V),e.filter($,H=>!G(H),V)]}e.split=S;function N($,G=!1,V=[],H){let T=V.slice(),z=$(j=>{T?T.push(j):xe.fire(j)});H&&H.add(z);let F=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new ke({onWillAddFirstListener(){z||(z=$(j=>xe.fire(j)),H&&H.add(z))},onDidAddFirstListener(){T&&(G?setTimeout(F):F())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return H&&H.add(xe),xe.event}e.buffer=N;function M($,G){return(V,H,T)=>{let z=G(new O);return $(function(F){let xe=z.evaluate(F);xe!==E&&V.call(H,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(V=>(G(V),V)),this}filter(G){return this.steps.push(V=>G(V)?V:E),this}reduce(G,V){let H=V;return this.steps.push(T=>(H=G(H,T),H)),this}latch(G=(V,H)=>V===H){let V=!0,H;return this.steps.push(T=>{let z=V||!G(T,H);return V=!1,H=T,z?T:E}),this}evaluate(G){for(let V of this.steps)if(G=V(G),G===E)break;return G}}function I($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.on(G,H),z=()=>$.removeListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromNodeEventEmitter=I;function A($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.addEventListener(G,H),z=()=>$.removeEventListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromDOMEventEmitter=A;function q($){return new Promise(G=>i($)(G))}e.toPromise=q;function R($){let G=new ke;return $.then(V=>{G.fire(V)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function re($,G){return $(V=>G.fire(V))}e.forward=re;function ue($,G,V){return G(V),$(H=>G(H))}e.runAndSubscribe=ue;class ye{constructor(G,V){this._observable=G,this._counter=0,this._hasChanged=!1;let H={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(H),V&&V.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,V){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 B($,G){return new ye($,G).emitter.event}e.fromObservable=B;function se($){return(G,V,H)=>{let T=0,z=!1,F={beginUpdate(){T++},endUpdate(){T--,T===0&&($.reportChanges(),z&&(z=!1,G.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};$.addObserver(F),$.reportChanges();let xe={dispose(){$.removeObserver(F)}};return H instanceof Fs?H.add(xe):Array.isArray(H)&&H.push(xe),xe}}e.fromObservableLight=se})(sn||(sn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),dt.None}if(this._disposed)return dt.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ni(()=>{o==null||o(),this._removeListener(a)});return s instanceof $s?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Ce,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Ce,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}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var ml=typeof navigator=="object"?navigator.userAgent:"",Jf=ml.indexOf("Firefox")>=0,gk=ml.indexOf("AppleWebKit")>=0,Yp=ml.indexOf("Chrome")>=0,xk=!Yp&&ml.indexOf("Safari")>=0;ml.indexOf("Electron/")>=0;ml.indexOf("Android")>=0;var rf=!1;if(typeof rs.matchMedia=="function"){let e=rs.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=rs.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(rs,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var al="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=al,_b=al,_k,hr,ga=globalThis,tn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?tn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(tn=process);var Ay,bk=typeof((Ay=tn==null?void 0:tn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(tn==null?void 0:tn.type)==="renderer",Ry;if(typeof tn=="object"){ep=tn.platform==="win32",tp=tn.platform==="darwin",xu=tn.platform==="linux",xu&&tn.env.SNAP&&tn.env.SNAP_REVISION,tn.env.CI||tn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=al,_u=al;let e=tn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||al,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(hr=navigator.userAgent,ep=hr.indexOf("Windows")>=0,tp=hr.indexOf("Macintosh")>=0,(hr.indexOf("Macintosh")>=0||hr.indexOf("iPad")>=0||hr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=hr.indexOf("Linux")>=0,(hr==null?void 0:hr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||al,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=hr,Ls=_u,Sk;(e=>{function t(){return Ls}e.value=t;function i(){return Ls.length===2?Ls==="en":Ls.length>=3?Ls[0]==="e"&&Ls[1]==="n"&&Ls[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ls==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.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}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var Ja=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ja&&Ja.clipboard&&Ja.clipboard.writeText,bb||Ja&&Ja.clipboard&&Ja.clipboard.readText;var Vp=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}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:nn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new Ce),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ni(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=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 Ce,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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:rs,disposables:new $s};e.set(rs.vscodeWindowId,t);let i=new Ce,s=new Ce,a=new Ce;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 $s,p={window:c,disposables:h.add(new $s)};return e.set(c.vscodeWindowId,p),h.add(ni(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ve(c,Pi.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:rs},getDocument(c){return Tr(c).document}}})(),Uk=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 Ve(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ve(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){gu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Pi={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"},qk=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=jn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=jn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=jn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=jn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=jn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=jn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=jn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=jn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=jn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=jn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=jn(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=jn(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=jn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=jn(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 jn(e){return typeof e=="number"?`${e}px`:e}function To(e){return new qk(e)}var r0=class{constructor(){this._hooks=new $s,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(ni(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ve(o,Pi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ve(o,Pi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var So=class an extends dt{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(nn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ve(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ve(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ve(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:rs,disposables:this._store}))}static addTarget(t){if(!an.isTouchDevice())return dt.None;an.INSTANCE||(an.INSTANCE=new an);let i=an.INSTANCE.targets.push(t);return ni(i)}static ignoreTarget(t){if(!an.isTouchDevice())return dt.None;an.INSTANCE||(an.INSTANCE=new an);let i=an.INSTANCE.ignoreTargets.push(t);return ni(i)}static isTouchDevice(){return"ontouchstart"in rs||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=an.HOLD_DELAY&&Math.abs(p.initialPageX-Un(p.rollingPageX))<30&&Math.abs(p.initialPageY-Un(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=Un(p.rollingPageX),_.pageY=Un(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=Un(p.rollingPageX),x=Un(p.rollingPageY),b=Un(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>an.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=an.SCROLL_FRICTION*x,h+=an.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};So.SCROLL_FRICTION=-.005,So.HOLD_DELAY=700,So.CLEAR_TAP_COUNT_TIME=400,di([Wk],So,"isTouchDevice",1);var Gk=So,Zp=class extends dt{onclick(e,t){this._register(Ve(e,Pi.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ve(e,Pi.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ve(e,Pi.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ve(e,Pi.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ve(e,Pi.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ve(e,Pi.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ve(e,Pi.INPUT,t))}onblur(e,t){this._register(Ve(e,Pi.BLUR,t))}onfocus(e,t){this._register(Ve(e,Pi.FOCUS,t))}onchange(e,t){this._register(Ve(e,Pi.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Pi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Pi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Vk=class ip{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 ip(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 ip(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}}},Kk=class extends dt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Zp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=To(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(Ve(this.domNode.domNode,Pi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=To(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(Ve(this.slider.domNode,Pi.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=Fk(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(e0&&c>e2){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()}},a0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{constructor(e,t,i){super(),this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Ce),this.onWillScroll=this._onWillScroll.event,this._options=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=To(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=To(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=To(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 Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(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,Rr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ve(this._listenOnDomNode,Pi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Rr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Rr&&(t.className+=" mac"),t}var ap=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 Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(nn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ni(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ni(()=>this._styleElement.remove())),this._register(nn.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(f=>this._handleScroll(f)))}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}};ap=di([Re(2,_n),Re(3,ss),Re(4,Hy),Re(5,pl),Re(6,bn),Re(7,as)],ap);var lp=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(ni(()=>{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()}};lp=di([Re(1,_n),Re(2,ss),Re(3,$o),Re(4,as)],lp);var c2=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)}},kr={full:0,left:0,center:0,right:0},Os={full:0,left:0,center:0,right:0},uo={full:0,left:0,center:0,right:0},ju=class extends dt{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ni(()=>{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);Os.full=this._canvas.width,Os.left=e,Os.center=t,Os.right=e,this._refreshDrawHeightConstants(),uo.full=1,uo.left=1,uo.center=1+Os.left,uo.right=1+Os.left+Os.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(uo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Os[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=di([Re(2,_n),Re(3,$o),Re(4,as),Re(5,bn),Re(6,pl),Re(7,ss)],ju);var me;(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=""))(me||(me={}));var bu;(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="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${me.ESC}\\`)(l0||(l0={}));var op=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)}}};op=di([Re(2,_n),Re(3,bn),Re(4,va),Re(5,as)],op);var Ii=0,Hi=0,Ui=0,ui=0,Db={css:"#00000000",rgba:0},Ti;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(Ti||(Ti={}));var ei;(e=>{function t(p,f){if(ui=(f.rgba&255)/255,ui===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Ii=v+Math.round((_-v)*ui),Hi=S+Math.round((x-S)*ui),Ui=N+Math.round((b-N)*ui);let M=Ti.toCss(Ii,Hi,Ui),E=Ti.toRgba(Ii,Hi,Ui);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ti.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Ii,Hi,Ui]=vu.toChannels(f),{css:Ti.toCss(Ii,Hi,Ui),rgba:f}}e.opaque=a;function o(p,f){return ui=Math.round(f*255),[Ii,Hi,Ui]=vu.toChannels(p.rgba),{css:Ti.toCss(Ii,Hi,Ui,ui),rgba:Ti.toRgba(Ii,Hi,Ui,ui)}}e.opacity=o;function c(p,f){return ui=p.rgba&255,o(p,ui*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ei||(ei={}));var li;(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 Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),Ti.toColor(Ii,Hi,Ui);case 5:return Ii=parseInt(a.slice(1,2).repeat(2),16),Hi=parseInt(a.slice(2,3).repeat(2),16),Ui=parseInt(a.slice(3,4).repeat(2),16),ui=parseInt(a.slice(4,5).repeat(2),16),Ti.toColor(Ii,Hi,Ui,ui);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 Ii=parseInt(o[1]),Hi=parseInt(o[2]),Ui=parseInt(o[3]),ui=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ti.toColor(Ii,Hi,Ui,ui);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),[Ii,Hi,Ui,ui]=t.getImageData(0,0,1,1).data,ui!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ti.toRgba(Ii,Hi,Ui,ui),css:a}}e.toColor=s})(li||(li={}));var pn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(ui=(h&255)/255,ui===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Ii=x+Math.round((p-x)*ui),Hi=b+Math.round((f-b)*ui),Ui=v+Math.round((_-v)*ui),Ti.toRgba(Ii,Hi,Ui)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(es(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=es(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=es(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,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})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function es(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Us.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=Y,q=this._workCell;if(b.length>0&&Y===b[0][0]&&T){let Se=b.shift(),He=this._isCellInSelection(Se[0],t);for(O=Se[0]+1;O=Se[1]),T?(U=!0,q=new u2(this._workCell,e.translateToString(!0,Se[0],Se[1]),Se[1]-Se[0]),z=Se[1]-1,V=q.getWidth()):B=Se[1]}let xe=this._isCellInSelection(Y,t),j=i&&Y===o,D=F&&Y>=f&&Y<=_,X=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Se=>{X=!0});let C=q.getChars()||Us;if(C===" "&&(q.isUnderline()||q.isOverline())&&(C=" "),be=V*h-p.get(C,q.isBold(),q.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&he||!xe&&!he&&q.bg===H)&&(xe&&he&&v.selectionForeground||q.fg===A)&&q.extended.ext===W&&D===R&&be===re&&!j&&!U&&!X&&T){q.isInvisible()?E+=Us:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(H=q.bg,A=q.fg,W=q.extended.ext,R=D,re=be,he=xe,U&&o>=Y&&o<=z&&(o=Y),!this._coreService.isCursorHidden&&j&&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(q.isBold()&&se.push("xterm-bold"),q.isItalic()&&se.push("xterm-italic"),q.isDim()&&se.push("xterm-dim"),q.isInvisible()?E=Us:E=q.getChars()||Us,q.isUnderline()&&(se.push(`xterm-underline-${q.extended.underlineStyle}`),E===" "&&(E=" "),!q.isUnderlineColorDefault()))if(q.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Uo.toColorRGB(q.getUnderlineColor()).join(",")})`;else{let Se=q.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&q.isBold()&&Se<8&&(Se+=8),N.style.textDecorationColor=v.ansi[Se].css}q.isOverline()&&(se.push("xterm-overline"),E===" "&&(E=" ")),q.isStrikethrough()&&se.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=q.getFgColor(),ae=q.getFgColorMode(),oe=q.getBgColor(),K=q.getBgColorMode(),de=!!q.isInverse();if(de){let Se=Z;Z=oe,oe=Se;let He=ae;ae=K,K=He}let ge,Me,Pe=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Se=>{Se.options.layer!=="top"&&Pe||(Se.backgroundColorRGB&&(K=50331648,oe=Se.backgroundColorRGB.rgba>>8&16777215,ge=Se.backgroundColorRGB),Se.foregroundColorRGB&&(ae=50331648,Z=Se.foregroundColorRGB.rgba>>8&16777215,Me=Se.foregroundColorRGB),Pe=Se.options.layer==="top")}),!Pe&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,Pe=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Pe&&se.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],se.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ti.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:de?(Fe=v.foreground,se.push("xterm-bg-257")):Fe=v.background}switch(ge||q.isDim()&&(ge=ei.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:q.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],q,ge,void 0)||se.push(`xterm-fg-${Z}`);break;case 50331648:let Se=Ti.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,Se,q,ge,Me)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,q,ge,Me)||de&&se.push("xterm-fg-257")}se.length&&(N.className=se.join(" "),se.length=0),!j&&!U&&!X&&T?M++:N.textContent=E,be!==this.defaultSpacing&&(N.style.letterSpacing=`${be}px`),x.push(N),Y=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=ei.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]}};cp=di([Re(1,Fy),Re(2,bn),Re(3,ss),Re(4,va),Re(5,$o),Re(6,pl)],cp);function Mb(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}},g2=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 x2(){return new g2}var lf="xterm-dom-renderer-owner-",tr="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",ho="xterm-focus",au="xterm-selection",_2=1,up=class extends dt{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new Ce).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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ni(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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: ${ei.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}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ho} .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} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ei.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ei.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ei.multiplyOpacity(ei.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(ho),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ho),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=di([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,ss),Re(13,pl)],up);var hp=class extends dt{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Ce),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};hp=di([Re(2,bn)],hp);var o0=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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=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 S2(this._window)),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Ce),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(nn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ve(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ve(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}},S2=class extends dt{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new hl),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ni(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ve(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)}},w2=class extends dt{constructor(){super(),this.linkProviders=[],this._register(ni(()=>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 Qp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Qp(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])}}};dp=di([Re(0,as),Re(1,Hu)],dp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,Fo=Uu?"node":navigator.userAgent,qo=Uu?"node":navigator.platform,u0=Fo.includes("Firefox"),E2=Fo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Fo);function N2(){if(!h0)return 0;let e=Fo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(qo),j2=qo==="iPad",T2=qo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(qo),Jp=qo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Fo),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=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 hl),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new hl),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 Ce),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Ce),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Ce),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ni(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ni(()=>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()}};fp=di([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,$o),Re(6,_n),Re(7,ss),Re(8,pl)],fp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Lo(Math.abs(a-e),Bo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Lo(p,Bo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Lo(g0(e,t,e,t-_a(t,a),!1,a).length,Bo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Lo(c,Bo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Lo(g0(e,c,i,h,p==="C",a).length,Bo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Bo(e,t){let i=t?"O":"[";return me.ESC+i+e}function Lo(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 Lb(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 of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=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 sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Ce),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Ce),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ni(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r +`))}},ok=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},ck=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},uk=0,nf=class{constructor(e){this.value=e,this.id=uk++}},hk=2,dk,ke=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new ak((t==null?void 0:t.onListenerError)??gu,((s=this._options)==null?void 0:s.leakWarningThreshold)??sk):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new rk(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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=si(()=>{o==null||o(),this._removeListener(a)});return s instanceof Fs?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Qf=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}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var pl=typeof navigator=="object"?navigator.userAgent:"",Jf=pl.indexOf("Firefox")>=0,gk=pl.indexOf("AppleWebKit")>=0,Yp=pl.indexOf("Chrome")>=0,xk=!Yp&&pl.indexOf("Safari")>=0;pl.indexOf("Electron/")>=0;pl.indexOf("Android")>=0;var rf=!1;if(typeof ss.matchMedia=="function"){let e=ss.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ss.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(ss,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var sl="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=sl,_b=sl,_k,fr,ga=globalThis,rn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?rn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(rn=process);var Ay,bk=typeof((Ay=rn==null?void 0:rn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(rn==null?void 0:rn.type)==="renderer",Ry;if(typeof rn=="object"){ep=rn.platform==="win32",tp=rn.platform==="darwin",xu=rn.platform==="linux",xu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=sl,_u=sl;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||sl,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(fr=navigator.userAgent,ep=fr.indexOf("Windows")>=0,tp=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||sl,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=fr,Os=_u,Sk;(e=>{function t(){return Os}e.value=t;function i(){return Os.length===2?Os==="en":Os.length>=3?Os[0]==="e"&&Os[1]==="n"&&Os[2]==="-":!1}e.isDefaultVariant=i;function s(){return Os==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.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}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var Qa=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Qa&&Qa.clipboard&&Qa.clipboard.writeText,bb||Qa&&Qa.clipboard&&Qa.clipboard.readText;var Vp=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}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:sn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=si(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=class nr{static fromArray(t){return new nr(i=>{i.emitMany(t)})}static fromPromise(t){return new nr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new nr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new nr(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 nr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return nr.map(this,t)}static filter(t,i){return new nr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return nr.filter(this,t)}static coalesce(t){return nr.filter(t,i=>!!i)}coalesce(){return nr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return nr.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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:ss,disposables:new Fs};e.set(ss.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 ht.None;let h=new Fs,p={window:c,disposables:h.add(new Fs)};return e.set(c.vscodeWindowId,p),h.add(si(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ke(c,Ui.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:ss},getDocument(c){return Tr(c).document}}})(),Uk=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 Ke(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ke(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){gu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Ui={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"},qk=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=En(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=En(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=En(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=En(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=En(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=En(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=En(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=En(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=En(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=En(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=En(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=En(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=En(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=En(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 En(e){return typeof e=="number"?`${e}px`:e}function To(e){return new qk(e)}var r0=class{constructor(){this._hooks=new Fs,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(si(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ke(o,Ui.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ke(o,Ui.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var So=class on extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ke(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ke(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ke(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:ss,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return si(i)}static ignoreTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return si(i)}static isTouchDevice(){return"ontouchstart"in ss||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=on.HOLD_DELAY&&Math.abs(p.initialPageX-$n(p.rollingPageX))<30&&Math.abs(p.initialPageY-$n(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=$n(p.rollingPageX),_.pageY=$n(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=$n(p.rollingPageX),x=$n(p.rollingPageY),b=$n(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>on.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};So.SCROLL_FRICTION=-.005,So.HOLD_DELAY=700,So.CLEAR_TAP_COUNT_TIME=400,fi([Wk],So,"isTouchDevice",1);var Gk=So,Zp=class extends ht{onclick(e,t){this._register(Ke(e,Ui.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ke(e,Ui.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ke(e,Ui.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ke(e,Ui.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ke(e,Ui.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ke(e,Ui.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ke(e,Ui.INPUT,t))}onblur(e,t){this._register(Ke(e,Ui.BLUR,t))}onfocus(e,t){this._register(Ke(e,Ui.FOCUS,t))}onchange(e,t){this._register(Ke(e,Ui.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Vk=class ip{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 ip(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 ip(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}}},Kk=class extends ht{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 Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Zp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=To(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(Ke(this.domNode.domNode,Ui.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=To(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(Ke(this.slider.domNode,Ui.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=Fk(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(e0&&c>e2){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()}},a0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{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=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=To(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=To(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=To(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 Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(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,Rr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ke(this._listenOnDomNode,Ui.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Rr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Rr&&(t.className+=" mac"),t}var ap=class extends ht{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 Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(si(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(si(()=>this._styleElement.remove())),this._register(sn.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(f=>this._handleScroll(f)))}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}};ap=fi([Re(2,_n),Re(3,as),Re(4,Hy),Re(5,fl),Re(6,bn),Re(7,ls)],ap);var lp=class extends ht{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(si(()=>{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()}};lp=fi([Re(1,_n),Re(2,as),Re(3,$o),Re(4,ls)],lp);var c2=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)}},kr={full:0,left:0,center:0,right:0},zs={full:0,left:0,center:0,right:0},uo={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(si(()=>{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);zs.full=this._canvas.width,zs.left=e,zs.center=t,zs.right=e,this._refreshDrawHeightConstants(),uo.full=1,uo.left=1,uo.center=1+zs.left,uo.right=1+zs.left+zs.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(uo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),zs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=fi([Re(2,_n),Re(3,$o),Re(4,ls),Re(5,bn),Re(6,fl),Re(7,as)],ju);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 bu;(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="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${pe.ESC}\\`)(l0||(l0={}));var op=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)}}};op=fi([Re(2,_n),Re(3,bn),Re(4,va),Re(5,ls)],op);var $i=0,Fi=0,qi=0,hi=0,Db={css:"#00000000",rgba:0},Ai;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(Ai||(Ai={}));var ni;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;$i=v+Math.round((_-v)*hi),Fi=S+Math.round((x-S)*hi),qi=N+Math.round((b-N)*hi);let M=Ai.toCss($i,Fi,qi),E=Ai.toRgba($i,Fi,qi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ai.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[$i,Fi,qi]=vu.toChannels(f),{css:Ai.toCss($i,Fi,qi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[$i,Fi,qi]=vu.toChannels(p.rgba),{css:Ai.toCss($i,Fi,qi,hi),rgba:Ai.toRgba($i,Fi,qi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ni||(ni={}));var oi;(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 $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),Ai.toColor($i,Fi,qi);case 5:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),Ai.toColor($i,Fi,qi,hi);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 $i=parseInt(o[1]),Fi=parseInt(o[2]),qi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ai.toColor($i,Fi,qi,hi);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),[$i,Fi,qi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ai.toRgba($i,Fi,qi,hi),css:a}}e.toColor=s})(oi||(oi={}));var pn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return $i=x+Math.round((p-x)*hi),Fi=b+Math.round((f-b)*hi),qi=v+Math.round((_-v)*hi),Ai.toRgba($i,Fi,qi)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,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})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||$s.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,F=this._workCell;if(b.length>0&&G===b[0][0]&&T){let we=b.shift(),He=this._isCellInSelection(we[0],t);for(O=we[0]+1;O=we[1]),T?(H=!0,F=new u2(this._workCell,e.translateToString(!0,we[0],we[1]),we[1]-we[0]),z=we[1]-1,V=F.getWidth()):B=we[1]}let xe=this._isCellInSelection(G,t),j=i&&G===o,D=$&&G>=f&&G<=_,X=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{X=!0});let C=F.getChars()||$s;if(C===" "&&(F.isUnderline()||F.isOverline())&&(C=" "),ye=V*h-p.get(C,F.isBold(),F.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&ue||!xe&&!ue&&F.bg===I)&&(xe&&ue&&v.selectionForeground||F.fg===A)&&F.extended.ext===q&&D===R&&ye===re&&!j&&!H&&!X&&T){F.isInvisible()?E+=$s:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=F.bg,A=F.fg,q=F.extended.ext,R=D,re=ye,ue=xe,H&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&j&&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(F.isBold()&&se.push("xterm-bold"),F.isItalic()&&se.push("xterm-italic"),F.isDim()&&se.push("xterm-dim"),F.isInvisible()?E=$s:E=F.getChars()||$s,F.isUnderline()&&(se.push(`xterm-underline-${F.extended.underlineStyle}`),E===" "&&(E=" "),!F.isUnderlineColorDefault()))if(F.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Uo.toColorRGB(F.getUnderlineColor()).join(",")})`;else{let we=F.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&F.isBold()&&we<8&&(we+=8),N.style.textDecorationColor=v.ansi[we].css}F.isOverline()&&(se.push("xterm-overline"),E===" "&&(E=" ")),F.isStrikethrough()&&se.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=F.getFgColor(),ae=F.getFgColorMode(),oe=F.getBgColor(),K=F.getBgColorMode(),he=!!F.isInverse();if(he){let we=Z;Z=oe,oe=we;let He=ae;ae=K,K=He}let ge,De,ze=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{we.options.layer!=="top"&&ze||(we.backgroundColorRGB&&(K=50331648,oe=we.backgroundColorRGB.rgba>>8&16777215,ge=we.backgroundColorRGB),we.foregroundColorRGB&&(ae=50331648,Z=we.foregroundColorRGB.rgba>>8&16777215,De=we.foregroundColorRGB),ze=we.options.layer==="top")}),!ze&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,ze=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),ze&&se.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],se.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ai.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:he?(Fe=v.foreground,se.push("xterm-bg-257")):Fe=v.background}switch(ge||F.isDim()&&(ge=ni.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:F.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],F,ge,void 0)||se.push(`xterm-fg-${Z}`);break;case 50331648:let we=Ai.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,we,F,ge,De)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,F,ge,De)||he&&se.push("xterm-fg-257")}se.length&&(N.className=se.join(" "),se.length=0),!j&&!H&&!X&&T?M++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=ni.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]}};cp=fi([Re(1,Fy),Re(2,bn),Re(3,as),Re(4,va),Re(5,$o),Re(6,fl)],cp);function Mb(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}},g2=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 x2(){return new g2}var lf="xterm-dom-renderer-owner-",ir="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",ho="xterm-focus",au="xterm-selection",_2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(ir),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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(si(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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} .${ir} 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} .${ir} { 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} .${ir} .xterm-dim { color: ${ni.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} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ni.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ni.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ni.multiplyOpacity(ni.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(ho),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ho),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=fi([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,as),Re(13,fl)],up);var hp=class extends ht{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 v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};hp=fi([Re(2,bn)],hp);var o0=class extends ht{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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=class extends ht{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 S2(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(sn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ke(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ke(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}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ul),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(si(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ke(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)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(si(()=>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 Qp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Qp(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])}}};dp=fi([Re(0,ls),Re(1,Hu)],dp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,Fo=Uu?"node":navigator.userAgent,qo=Uu?"node":navigator.platform,u0=Fo.includes("Firefox"),E2=Fo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Fo);function N2(){if(!h0)return 0;let e=Fo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(qo),j2=qo==="iPad",T2=qo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(qo),Jp=qo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Fo),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{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 ul),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new ul),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 k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(si(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=si(()=>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()}};fp=fi([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,$o),Re(6,_n),Re(7,as),Re(8,fl)],fp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Lo(Math.abs(a-e),Bo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Lo(p,Bo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Lo(g0(e,t,e,t-_a(t,a),!1,a).length,Bo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Lo(c,Bo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Lo(g0(e,c,i,h,p==="C",a).length,Bo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Bo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Lo(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 Lb(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 of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=class extends ht{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 ar,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=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(si(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&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=Lb(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=Qp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?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(),F2)}_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&&!(Au&&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,f=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+=O-1,p+=O-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):H>1&&(b+=H-1,h-=H-1),h--,M--}for(;E1&&(v+=H-1,p+=H-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let O=this._bufferService.cols-E.start;S-=O,N+=O}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};pp=di([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,as),Re(8,ss)],pp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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()}},Di=Object.freeze((()=>{let e=[li.toColor("#2e3436"),li.toColor("#cc0000"),li.toColor("#4e9a06"),li.toColor("#c4a000"),li.toColor("#3465a4"),li.toColor("#75507b"),li.toColor("#06989a"),li.toColor("#d3d7cf"),li.toColor("#555753"),li.toColor("#ef2929"),li.toColor("#8ae234"),li.toColor("#fce94f"),li.toColor("#729fcf"),li.toColor("#ad7fa8"),li.toColor("#34e2e2"),li.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:Ti.toCss(s,a,o),rgba:Ti.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ti.toCss(s,s,s),rgba:Ti.toRgba(s,s,s)})}return e})()),fa=li.toColor("#ffffff"),wo=li.toColor("#000000"),Pb=li.toColor("#ffffff"),Ib=wo,fo={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends dt{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new Ce),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:wo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:fo,selectionBackgroundOpaque:ei.blend(wo,fo),selectionInactiveBackgroundTransparent:fo,selectionInactiveBackgroundOpaque:ei.blend(wo,fo),scrollbarSliderBackground:ei.opacity(fa,.2),scrollbarSliderHoverBackground:ei.opacity(fa,.4),scrollbarSliderActiveBackground:ei.opacity(fa,.5),overviewRulerBorder:fa,ansi:Di.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=It(e.foreground,fa),t.background=It(e.background,wo),t.cursor=ei.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ei.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,fo),t.selectionBackgroundOpaque=ei.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ei.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ei.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ei.opacity(t.selectionBackgroundTransparent,.3)),ei.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ei.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ei.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ei.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ei.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Di.slice(),t.ansi[0]=It(e.black,Di[0]),t.ansi[1]=It(e.red,Di[1]),t.ansi[2]=It(e.green,Di[2]),t.ansi[3]=It(e.yellow,Di[3]),t.ansi[4]=It(e.blue,Di[4]),t.ansi[5]=It(e.magenta,Di[5]),t.ansi[6]=It(e.cyan,Di[6]),t.ansi[7]=It(e.white,Di[7]),t.ansi[8]=It(e.brightBlack,Di[8]),t.ansi[9]=It(e.brightRed,Di[9]),t.ansi[10]=It(e.brightGreen,Di[10]),t.ansi[11]=It(e.brightYellow,Di[11]),t.ansi[12]=It(e.brightBlue,Di[12]),t.ansi[13]=It(e.brightMagenta,Di[13]),t.ansi[14]=It(e.brightCyan,Di[14]),t.ansi[15]=It(e.brightWhite,Di[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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=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=X2[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?Is(i&2097151):""}isProtected(t){return this._data[t*ht+2]&536870912}loadCell(t,i){return lu=t*ht,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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]+=Is(i):a&2097151?(this._combined[t]=Is(a&2097151)+Is(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*cf=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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cOo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Oo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new Ce),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Li={},pa=Li.B;Li[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Li.A={"#":"£"};Li.B=void 0;Li[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Li.C=Li[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Li.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Li.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Li.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Li.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Li.E=Li[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Li.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Li.H=Li[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Li["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=ji.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=sr.fromCharData([0,Oy,1,0]),this._whitespaceCell=sr.fromCharData([0,Us,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new Co(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&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=ji);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 Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(ji),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 Co(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(ji),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(ji),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 H=this.ybase+this.y;if(H>=c&&H0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let H=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-H,N-H,H,!0),N-=H,N===0&&(S--,N=_[S]),E-=H,E===0){M--;let A=Math.max(M,0);E=Oo(p,A,this._cols)}}for(let H=0;H0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends dt{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Ce),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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,xp=class extends dt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};xp=di([Re(0,bn)],xp);var el={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends dt{constructor(e){super(),this._onOptionChange=this._register(new Ce),this.onOptionChange=this._onOptionChange.event;let t={...el};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(ni(()=>{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 el))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in el))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=el[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=el[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:el[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 aE(e){return e==="block"||e==="underline"||e==="bar"}function ko(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]&&ko(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=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 Ce),this.onData=this._onData.event,this._onUserInput=this._register(new Ce),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Ce),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ko(Fb),this.decPrivateModes=ko(qb)}reset(){this.modes=ko(Fb),this.decPrivateModes=ko(qb)}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))}};_p=di([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={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 uf(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 hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=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 Ce),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};bp=di([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[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]],lE=[[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]],Mi;function oE(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=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Ce,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 po=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 vp;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>po?po: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>po?po: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,po):t}},mo=[],dE=class{constructor(){this._state=0,this._active=mo,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=mo}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=mo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||mo,!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",Iu(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=mo,this._id=-1,this._state=0}}},$n=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+=Iu(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}},go=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=go,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}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=go,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||go,!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",Iu(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=go,this._ident=0}},Eo=new S0;Eo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=Eo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Eo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=Eo,this._data="",this._hitLimit=!1,i));return this._params=Eo,this._data="",this._hitLimit=!1,t}},pE=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})(),gE=class extends dt{constructor(e=mE){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 S0,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(ni(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},zs=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends dt{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ji.clone(),this._eraseAttrDataInternal=ji.clone(),this._onRequestBell=this._register(new Ce),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Ce),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Ce),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Ce),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Ce),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Ce),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Ce),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Ce),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Ce),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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new $n(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new $n(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new $n(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new $n(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new $n(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new $n(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new $n(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new $n(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new $n(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new $n(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new $n(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new $n(f=>this.restoreCursorColor(f))),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 f in Li)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>zs&&(o=this._parseStack.position+zs)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthzs)for(let f=o;f0&&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,O=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof Co&&x.copyCellsFrom(E,O,0,M,!1);O=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new $n(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 f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Uo.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=ji.fg,e.bg=ji.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|=ji.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=ji.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|=ji.fg&16777215,s.bg&=-67108864,s.bg|=ji.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.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(`${me.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=ji.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(!Zb(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(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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=ji.clone(),this._eraseAttrDataInternal=ji.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(`${me.ESC}${c}${me.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)}},yp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=di([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=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 Ce),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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},Sp=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)))}};Sp=di([Re(0,_n)],Sp);var iv=!1,kE=class extends dt{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new hl),this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Ce),this._instantiationService=new K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(nn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(nn.forward(this._bufferService.onResize,this._onResize)),this._register(nn.forward(this.coreService.onData,this._onData)),this._register(nn.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(nn.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Ce),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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ni(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.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=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=EE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.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=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var vi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(vi=this._search(t),vi===-1)||this._getKey(this._array[vi])!==t)return!1;do if(this._array[vi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vi),!0;while(++via-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&&(vi=this._search(e),!(vi<0||vi>=this._array.length)&&this._getKey(this._array[vi])===e))do yield this._array[vi];while(++vi=this._array.length)&&this._getKey(this._array[vi])===e))do t(this._array[vi]);while(++vi=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}},pf=0,nv=0,TE=class extends dt{constructor(){super(),this._decorations=new jE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new Ce),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Ce),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ni(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&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)}},rv=20,Du=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 DE(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(Ve(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ni(()=>{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===rv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;xa(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(Ve(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ve(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ve(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ve(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,xa(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}}};wp=di([Re(1,Wp),Re(2,as),Re(3,_n),Re(4,qy)],wp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new hl),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new hl),this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Ce),this.onKey=this._onKey.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Ce),this.onBell=this._onBell.event,this._onFocus=this._register(new Ce),this._onBlur=this._register(new Ce),this._onA11yCharEmitter=this._register(new Ce),this._onA11yTabEmitter=this._register(new Ce),this._onWillOpen=this._register(new Ce),this._setup(),this._decorationService=this._instantiationService.createInstance(TE),this._instantiationService.setService($o,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(nn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(nn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(nn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(nn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ni(()=>{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=ei.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ti.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ti.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(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.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(me.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(Ve(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ve(this.textarea,"paste",e)),this._register(Ve(this.element,"paste",e)),u0?this._register(Ve(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ve(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ve(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ve(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ve(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ve(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ve(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ve(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ve(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ve(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(Ve(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",Uf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ss,this._coreBrowserService),this._register(Ve(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ve(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(pl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(as,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(nn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ve(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ve(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(Ve(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.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){By(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=NE(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===me.ETX||i.key===me.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)&&(LE(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)}},sv=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 zE(t)}getNullCell(){return new sr}},PE=class extends dt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Ce),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Er=0,$E=class extends dt{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&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=Lb(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=Qp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?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(),F2)}_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&&!(Au&&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,f=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+=O-1,p+=O-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let O=this._bufferService.cols-E.start;S-=O,N+=O}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};pp=fi([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,ls),Re(8,as)],pp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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()}},Bi=Object.freeze((()=>{let e=[oi.toColor("#2e3436"),oi.toColor("#cc0000"),oi.toColor("#4e9a06"),oi.toColor("#c4a000"),oi.toColor("#3465a4"),oi.toColor("#75507b"),oi.toColor("#06989a"),oi.toColor("#d3d7cf"),oi.toColor("#555753"),oi.toColor("#ef2929"),oi.toColor("#8ae234"),oi.toColor("#fce94f"),oi.toColor("#729fcf"),oi.toColor("#ad7fa8"),oi.toColor("#34e2e2"),oi.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:Ai.toCss(s,a,o),rgba:Ai.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ai.toCss(s,s,s),rgba:Ai.toRgba(s,s,s)})}return e})()),fa=oi.toColor("#ffffff"),wo=oi.toColor("#000000"),Pb=oi.toColor("#ffffff"),Ib=wo,fo={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:wo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:fo,selectionBackgroundOpaque:ni.blend(wo,fo),selectionInactiveBackgroundTransparent:fo,selectionInactiveBackgroundOpaque:ni.blend(wo,fo),scrollbarSliderBackground:ni.opacity(fa,.2),scrollbarSliderHoverBackground:ni.opacity(fa,.4),scrollbarSliderActiveBackground:ni.opacity(fa,.5),overviewRulerBorder:fa,ansi:Bi.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=It(e.foreground,fa),t.background=It(e.background,wo),t.cursor=ni.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ni.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,fo),t.selectionBackgroundOpaque=ni.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ni.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ni.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ni.opacity(t.selectionBackgroundTransparent,.3)),ni.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ni.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ni.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ni.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ni.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Bi.slice(),t.ansi[0]=It(e.black,Bi[0]),t.ansi[1]=It(e.red,Bi[1]),t.ansi[2]=It(e.green,Bi[2]),t.ansi[3]=It(e.yellow,Bi[3]),t.ansi[4]=It(e.blue,Bi[4]),t.ansi[5]=It(e.magenta,Bi[5]),t.ansi[6]=It(e.cyan,Bi[6]),t.ansi[7]=It(e.white,Bi[7]),t.ansi[8]=It(e.brightBlack,Bi[8]),t.ansi[9]=It(e.brightRed,Bi[9]),t.ansi[10]=It(e.brightGreen,Bi[10]),t.ansi[11]=It(e.brightYellow,Bi[11]),t.ansi[12]=It(e.brightBlue,Bi[12]),t.ansi[13]=It(e.brightMagenta,Bi[13]),t.ansi[14]=It(e.brightCyan,Bi[14]),t.ansi[15]=It(e.brightWhite,Bi[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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=class extends ht{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=X2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Hs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Hs(i):a&2097151?(this._combined[t]=Hs(a&2097151)+Hs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cOo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Oo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._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(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,zi={},pa=zi.B;zi[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:"≥","{":"π","|":"≠","}":"£","~":"·"};zi.A={"#":"£"};zi.B=void 0;zi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};zi.C=zi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};zi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};zi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};zi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};zi.E=zi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};zi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};zi.H=zi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=Ti.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=ar.fromCharData([0,Oy,1,0]),this._whitespaceCell=ar.fromCharData([0,$s,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new Co(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&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ti);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 Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ti),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 Co(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ti),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ti),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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let A=Math.max(M,0);E=Oo(p,A,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends ht{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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,xp=class extends ht{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,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};xp=fi([Re(0,bn)],xp);var Ja={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...Ja};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(si(()=>{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 Ja))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Ja))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=Ja[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ja[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:Ja[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 aE(e){return e==="block"||e==="underline"||e==="bar"}function ko(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]&&ko(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{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=ko(Fb),this.decPrivateModes=ko(qb)}reset(){this.modes=ko(Fb),this.decPrivateModes=ko(qb)}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))}};_p=fi([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={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 uf(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 hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{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(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};bp=fi([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[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]],lE=[[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]],Li;function oE(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=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 po=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 vp;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>po?po: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>po?po: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,po):t}},mo=[],dE=class{constructor(){this._state=0,this._active=mo,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=mo}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=mo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||mo,!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",Iu(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=mo,this._id=-1,this._state=0}}},Fn=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+=Iu(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}},go=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=go,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}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=go,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||go,!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",Iu(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=go,this._ident=0}},Eo=new S0;Eo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=Eo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Eo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=Eo,this._data="",this._hitLimit=!1,i));return this._params=Eo,this._data="",this._hitLimit=!1,t}},pE=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(rr,0,2,0),e.add(rr,8,5,8),e.add(rr,6,0,6),e.add(rr,11,0,11),e.add(rr,13,13,13),e})(),gE=class extends ht{constructor(e=mE){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 S0,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(si(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ps=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ti.clone(),this._eraseAttrDataInternal=Ti.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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!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(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Fn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Fn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Fn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Fn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Fn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Fn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Fn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Fn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Fn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Fn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Fn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Fn(f=>this.restoreCursorColor(f))),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 f in zi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>Ps&&(o=this._parseStack.position+Ps)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthPs)for(let f=o;f0&&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,O=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof Co&&x.copyCellsFrom(E,O,0,M,!1);O=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Fn(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 f=1;f0||(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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Uo.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=Ti.fg,e.bg=Ti.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|=Ti.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ti.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|=Ti.fg&16777215,s.bg&=-67108864,s.bg|=Ti.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=Ti.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(!Zb(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>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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=Ti.clone(),this._eraseAttrDataInternal=Ti.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 ar;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)}},yp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=fi([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},Sp=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)))}};Sp=fi([Re(0,_n)],Sp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ul),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 K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(sn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(sn.forward(this._bufferService.onResize,this._onResize)),this._register(sn.forward(this.coreService.onData,this._onData)),this._register(sn.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(sn.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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=si(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=EE[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,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=pe.ESC+f}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 vi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(vi=this._search(t),vi===-1)||this._getKey(this._array[vi])!==t)return!1;do if(this._array[vi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vi),!0;while(++via-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&&(vi=this._search(e),!(vi<0||vi>=this._array.length)&&this._getKey(this._array[vi])===e))do yield this._array[vi];while(++vi=this._array.length)&&this._getKey(this._array[vi])===e))do t(this._array[vi]);while(++vi=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}},pf=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(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(si(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&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)}},rv=20,Du=class extends ht{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 DE(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(Ke(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(si(()=>{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===rv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;xa(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(Ke(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ke(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ke(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ke(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,xa(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}}};wp=fi([Re(1,Wp),Re(2,ls),Re(3,_n),Re(4,qy)],wp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new ul),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ul),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(TE),this._instantiationService.setService($o,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(si(()=>{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=ni.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ai.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ai.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(Du,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(Ke(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ke(this.textarea,"paste",e)),this._register(Ke(this.element,"paste",e)),u0?this._register(Ke(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ke(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ke(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ke(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ke(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ke(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ke(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ke(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ke(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ke(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(Ke(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",Uf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(as,this._coreBrowserService),this._register(Ke(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ke(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(fl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(ls,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ke(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ke(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(Ke(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.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){By(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=NE(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)&&(LE(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 ar)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=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 zE(t)}getNullCell(){return new ar}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Er=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT @@ -94,48 +94,48 @@ 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 $i=0,Fi=0,qi=0,hi=0,ln;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(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})(ln||(ln={}));var GE;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;$i=v+Math.round((_-v)*hi),Fi=S+Math.round((x-S)*hi),qi=N+Math.round((b-N)*hi);let M=ln.toCss($i,Fi,qi),E=ln.toRgba($i,Fi,qi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return ln.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[$i,Fi,qi]=Su.toChannels(f),{css:ln.toCss($i,Fi,qi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[$i,Fi,qi]=Su.toChannels(p.rgba),{css:ln.toCss($i,Fi,qi,hi),rgba:ln.toRgba($i,Fi,qi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var en;(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 $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),ln.toColor($i,Fi,qi);case 5:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),ln.toColor($i,Fi,qi,hi);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 $i=parseInt(o[1]),Fi=parseInt(o[2]),qi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),ln.toColor($i,Fi,qi,hi);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),[$i,Fi,qi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:ln.toRgba($i,Fi,qi,hi),css:a}}e.toColor=s})(en||(en={}));var mn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return $i=x+Math.round((p-x)*hi),Fi=b+Math.round((f-b)*hi),qi=v+Math.round((_-v)*hi),ln.toRgba($i,Fi,qi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,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})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e{let e=[en.toColor("#2e3436"),en.toColor("#cc0000"),en.toColor("#4e9a06"),en.toColor("#c4a000"),en.toColor("#3465a4"),en.toColor("#75507b"),en.toColor("#06989a"),en.toColor("#d3d7cf"),en.toColor("#555753"),en.toColor("#ef2929"),en.toColor("#8ae234"),en.toColor("#fce94f"),en.toColor("#729fcf"),en.toColor("#ad7fa8"),en.toColor("#34e2e2"),en.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:ln.toCss(s,a,o),rgba:ln.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:ln.toCss(s,s,s),rgba:ln.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!is(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&is(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&is(c,p)&&is(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=!C0(e,t),a=!is(e,t),o=!k0(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?!is(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(is(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&&(is(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!is(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",tl="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${tl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${tl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${tl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${tl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${tl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${tl}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,Fs="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Fs)||s.createObjectStore(Fs)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function il(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction(Fs,"readwrite");c.objectStore(Fs).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction(Fs,"readonly").objectStore(Fs).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction(Fs,"readwrite");a.objectStore(Fs).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Bi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[O,H]=w.useState(new Set),[A,W]=w.useState(null),[R,re]=w.useState(null),[he,be]=w.useState(!1),[B,se]=w.useState(!1),F=eN(x,_),Y=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const U=w.useCallback(K=>{var ge;const{width:de}=K.container.getBoundingClientRect();if(!(de<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[de,ge]of Bi)ge.container.style.display=de===K?"block":"none";if(K){const de=Bi.get(K);de&&setTimeout(()=>U(de),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const q=w.useRef({});w.useEffect(()=>{q.current=f||{}},[f]);const xe=w.useCallback((K,de,ge)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Pe=z.current[K]?"&bypass=true":"",Fe=q.current[K],Se=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${Pe}${Se}`);He.onopen=()=>{de.connected=!0,de._retried=!1,H(at=>{const et=new Set(at);return et.delete(K),et}),He.send(JSON.stringify({type:"resize",cols:de.term.cols,rows:de.term.rows}))};let Je=!0;He.onmessage=at=>{if(Je&&(Je=!1,typeof at.data=="string"&&at.data===QE)){de.term.reset(),mf(K).catch(()=>{});return}de.term.write(typeof at.data=="string"?lv(at.data):at.data)},He.onclose=at=>{if(de.connected=!1,de.ws===He){de.ws=null;try{const et=de.serialize.serialize();il(K,et).catch(()=>{})}catch{}if(at.code===4e3&&!de._retried){de._retried=!0,de.term.write(`\r + */var Wi=0,Gi=0,Yi=0,di=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(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})(cn||(cn={}));var GE;(e=>{function t(p,f){if(di=(f.rgba&255)/255,di===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Wi=v+Math.round((_-v)*di),Gi=S+Math.round((x-S)*di),Yi=N+Math.round((b-N)*di);let M=cn.toCss(Wi,Gi,Yi),E=cn.toRgba(Wi,Gi,Yi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Wi,Gi,Yi]=Su.toChannels(f),{css:cn.toCss(Wi,Gi,Yi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[Wi,Gi,Yi]=Su.toChannels(p.rgba),{css:cn.toCss(Wi,Gi,Yi,di),rgba:cn.toRgba(Wi,Gi,Yi,di)}}e.opacity=o;function c(p,f){return di=p.rgba&255,o(p,di*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var nn;(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 Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Wi,Gi,Yi);case 5:return Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),di=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Wi,Gi,Yi,di);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 Wi=parseInt(o[1]),Gi=parseInt(o[2]),Yi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Wi,Gi,Yi,di);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),[Wi,Gi,Yi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Wi,Gi,Yi,di),css:a}}e.toColor=s})(nn||(nn={}));var mn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(di=(h&255)/255,di===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Wi=x+Math.round((p-x)*di),Gi=b+Math.round((f-b)*di),Yi=v+Math.round((_-v)*di),cn.toRgba(Wi,Gi,Yi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(is(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=is(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,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})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function is(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.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:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!ns(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&ns(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&ns(c,p)&&ns(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=!C0(e,t),a=!ns(e,t),o=!k0(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?!ns(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(ns(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&&(ns(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!ns(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",el="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${el}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${el}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${el}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${el}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${el}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${el}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,qs="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(qs)||s.createObjectStore(qs)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function tl(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction(qs,"readwrite");c.objectStore(qs).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction(qs,"readonly").objectStore(qs).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction(qs,"readwrite");a.objectStore(qs).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Oi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[O,I]=w.useState(new Set),[A,q]=w.useState(null),[R,re]=w.useState(null),[ue,ye]=w.useState(!1),[B,se]=w.useState(!1),$=eN(x,_),G=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const H=w.useCallback(K=>{var ge;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[he,ge]of Oi)ge.container.style.display=he===K?"block":"none";if(K){const he=Oi.get(K);he&&setTimeout(()=>H(he),50)}},[H]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const F=w.useRef({});w.useEffect(()=>{F.current=f||{}},[f]);const xe=w.useCallback((K,he,ge)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",ze=z.current[K]?"&bypass=true":"",Fe=F.current[K],we=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${ze}${we}`);He.onopen=()=>{he.connected=!0,he._retried=!1,I(st=>{const it=new Set(st);return it.delete(K),it}),He.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let tt=!0;He.onmessage=st=>{if(tt&&(tt=!1,typeof st.data=="string"&&st.data===QE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof st.data=="string"?lv(st.data):st.data)},He.onclose=st=>{if(he.connected=!1,he.ws===He){he.ws=null;try{const it=he.serialize.serialize();tl(K,it).catch(()=>{})}catch{}if(st.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),V.current(K,de,!1);return}H(et=>new Set(et).add(K))}},de.term.onData(at=>{He.readyState===WebSocket.OPEN&&He.send(at)}),de.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,de)=>{if(!S.current||Bi.has(K))return;const{resume:ge=!1,autoConnect:Me=!0}=de??{},Pe=document.createElement("div");Pe.style.width="100%",Pe.style.height="100%",Pe.style.display="none",Pe.style.paddingLeft="10px",Pe.style.boxSizing="border-box",S.current.appendChild(Pe);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),Se=new WE,He=new XE;Fe.loadAddon(Se),Fe.loadAddon(He),Fe.open(Pe);const Je={term:Fe,fit:Se,serialize:He,ws:null,container:Pe,observer:null,connected:!1},at=new ResizeObserver(()=>{var jt;const{width:et}=Pe.getBoundingClientRect();if(!(et<50))try{Se.fit(),((jt=Je.ws)==null?void 0:jt.readyState)===WebSocket.OPEN&&Je.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});at.observe(Pe),Je.observer=at,Bi.set(K,Je),E(et=>[...et,K]);try{const et=await rN(K);if(et){const jt=lv(et);Fe.write(jt),jt!==et&&il(K,jt).catch(()=>{})}}catch{}Me?xe(K,Je,ge):H(et=>new Set(et).add(K)),setTimeout(()=>U(Je),50)},[xe,U]),D=w.useCallback(async(K,de)=>{const ge=Bi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),de||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,de))},[xe]),X=w.useCallback(K=>{const de=Bi.get(K);if(de){try{const ge=de.serialize.serialize();il(K,ge).catch(()=>{})}catch{}de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),Bi.delete(K),E(ge=>ge.filter(Me=>Me!==K)),H(ge=>{const Me=new Set(ge);return Me.delete(K),Me}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const de=Bi.get(K);de&&(((ge=de.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&de.ws.send(`exit -`),mf(K).catch(()=>{}),de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),Bi.delete(K),E(Me=>Me.filter(Pe=>Pe!==K)),H(Me=>{const Pe=new Set(Me);return Pe.delete(K),Pe}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,de,ge)=>{const Me=Bi.get(K);if(!Me||Bi.has(de)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:de,...ge??{}})})).ok)return!1;Bi.delete(K),Bi.set(de,Me);try{const Fe=Me.serialize.serialize();await mf(K),await il(de,Fe)}catch{}return E(Fe=>Fe.map(Se=>Se===K?de:Se)),H(Fe=>{if(!Fe.has(K))return Fe;const Se=new Set(Fe);return Se.delete(K),Se.add(de),Se}),(Me.connected||Me.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(de)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),V.current(de,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if(F){T(null);return}if(Y){T(null);return}Bi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Bi.has(t)){const de=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!de}),T(t)}}).catch(()=>{Bi.has(t)||(j(t),T(t))})}},[t,j,T,F,Y]),w.useEffect(()=>{const K=setInterval(()=>{for(const[de,ge]of Bi)if(ge.connected)try{const Me=ge.serialize.serialize();il(de,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,de]of Bi){try{const ge=de.serialize.serialize();il(K,ge).catch(()=>{})}catch{}de.observer.disconnect(),de.ws&&de.ws.close(),de.term.dispose(),de.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Bi.clear()},[]);const ae=t?O.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:de=>{de.stopPropagation(),K.startsWith("_new_")?W(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>W(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))?d.jsx("button",{onClick:()=>re(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!F&&!Y&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),be(!0),setTimeout(()=>be(!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"})]})]})]})}),Y&&!F&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){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:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>W(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;W(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>re(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;re(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Wo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Wo.prototype.normal={};Wo.prototype.property={};Wo.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Wo(i,s,t)}function Cp(e){return e.toLowerCase()}class Rn{constructor(t,i){this.attribute=i,this.property=t}}Rn.prototype.attribute="";Rn.prototype.booleanish=!1;Rn.prototype.boolean=!1;Rn.prototype.commaOrSpaceSeparated=!1;Rn.prototype.commaSeparated=!1;Rn.prototype.defined=!1;Rn.prototype.mustUseProperty=!1;Rn.prototype.number=!1;Rn.prototype.overloadedBoolean=!1;Rn.prototype.property="";Rn.prototype.spaceSeparated=!1;Rn.prototype.space=void 0;let dN=0;const ot=ya(),Ni=ya(),kp=ya(),ve=ya(),Kt=ya(),ol=ya(),Fn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Ni,commaOrSpaceSeparated:Fn,commaSeparated:ol,number:ve,overloadedBoolean:kp,spaceSeparated:Kt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Rn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var nl={},xf,pv;function wN(){if(pv)return xf;pv=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=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var O=1,H=1;function A(V){var U=V.match(t);U&&(O+=U.length);var T=V.lastIndexOf(p);H=~T?V.length-T:H+V.length}function W(){var V={line:O,column:H};return function(U){return U.position=new R(V),be(),U}}function R(V){this.start=V,this.end={line:O,column:H},this.source=E.source}R.prototype.content=M;function re(V){var U=new Error(E.source+":"+O+":"+H+": "+V);if(U.reason=V,U.filename=E.source,U.line=O,U.column=H,U.source=M,!E.silent)throw U}function he(V){var U=V.exec(M);if(U){var T=U[0];return A(T),M=M.slice(T.length),U}}function be(){he(i)}function B(V){var U;for(V=V||[];U=se();)U!==!1&&V.push(U);return V}function se(){var V=W();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var U=2;x!=M.charAt(U)&&(_!=M.charAt(U)||f!=M.charAt(U+1));)++U;if(U+=2,x===M.charAt(U-1))return re("End of comment missing");var T=M.slice(2,U-2);return H+=2,A(T),M=M.slice(U),H+=2,V({type:b,comment:T})}}function F(){var V=W(),U=he(s);if(U){if(se(),!he(a))return re("property missing ':'");var T=he(o),z=V({type:v,property:N(U[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return he(c),z}}function Y(){var V=[];B(V);for(var U;U=F();)U!==!1&&(V.push(U),B(V));return V}return be(),Y()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return nl;mv=1;var e=nl&&nl.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(nl,"__esModule",{value:!0}),nl.default=i;const t=e(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return nl}var xo={},gv;function kN(){if(gv)return xo;gv=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return xo.camelCase=p,xo}var _o,xv;function EN(){if(xv)return _o;xv=1;var e=_o&&_o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,_o=s,_o}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(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 L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ao(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class cn 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=Ao(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}}cn.prototype.file="";cn.prototype.name="";cn.prototype.reason="";cn.prototype.message="";cn.prototype.stack="";cn.prototype.column=void 0;cn.prototype.line=void 0;cn.prototype.ancestors=void 0;cn.prototype.cause=void 0;cn.prototype.fatal=void 0;cn.prototype.place=void 0;cn.prototype.ruleId=void 0;cn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}zo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);zo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 zo(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 zo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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?(qn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(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 xn=qs(/[A-Za-z]/),on=qs(/[\dA-Za-z]/),JN=qs(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=qs(/\d/),e5=qs(/[\dA-Fa-f]/),t5=qs(/[!-/:-@[-`{-~]/);function We(e){return e!==null&&e<-2}function Wt(e){return e!==null&&(e<0||e===32)}function gt(e){return e===-2||e===-1||e===32}const Fu=qs(new RegExp("\\p{P}|\\p{S}","u")),ba=qs(/\s/);function qs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function xl(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 yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return gt(p)?(e.enter(i),h(p)):t(p)}function h(p){return gt(p)&&o++c))return;const re=t.events.length;let he=re,be,B;for(;he--;)if(t.events[he][0]==="exit"&&t.events[he][1].type==="chunkFlow"){if(be){B=t.events[he][1].end;break}be=!0}for(E(s),R=re;RH;){const W=i[A];t.containerState=W[1],W[0].exit.call(t,e)}i.length=H}function O(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function dl(e){if(e===null||Wt(e)||ba(e))return 1;if(Fu(e))return 2}function qu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,qn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&>(R)?yt(e,O,"linePrefix",o+1)(R):O(R)}function O(R){return R===null||We(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),H(R))}function H(R){return R===null||We(R)?(e.exit("codeFlowValue"),O(R)):(e.consume(R),H)}function A(R){return e.exit("codeFenced"),t(R)}function W(R,re,he){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),se}function se(U){return R.enter("codeFencedFence"),gt(U)?yt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),Y(U)):he(U)}function Y(U){return U===h?(be++,R.consume(U),Y):be>=c?(R.exit("codeFencedFenceSequence"),gt(U)?yt(R,V,"whitespace")(U):V(U)):he(U)}function V(U){return U===null||We(U)?(R.exit("codeFencedFence"),re(U)):he(U)}}}function _5(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 bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):We(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||We(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):We(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(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):We(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&bo(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),bo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bo(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Mu(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||We(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||Wt(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):We(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||We(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!gt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):We(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||We(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ro(e,t){let i;return s;function s(a){return We(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):gt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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 Wt(v)?Ro(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return gt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||We(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return Wt(h)?Ro(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return gt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||We(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return We(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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"},qn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(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||Wt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||We(_)?(e.exit("atxHeading"),t(_)):gt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Wt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:F:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||Wt(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):F(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?O(C):H(C))}return C===45||on(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function O(C){return gt(C)?(e.consume(C),O):B(C)}function H(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):gt(C)?(e.consume(C),H):B(C)}function A(C){return C===45||C===46||C===58||C===95||on(C)?(e.consume(C),A):W(C)}function W(C){return C===61?(e.consume(C),R):gt(C)?(e.consume(C),W):H(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,re):gt(C)?(e.consume(C),R):he(C)}function re(C){return C===p?(e.consume(C),p=null,be):C===null||We(C)?i(C):(e.consume(C),re)}function he(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Wt(C)?W(C):(e.consume(C),he)}function be(C){return C===47||C===62||gt(C)?H(C):i(C)}function B(C){return C===62?(e.consume(C),se):i(C)}function se(C){return C===null||We(C)?F(C):gt(C)?(e.consume(C),se):i(C)}function F(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):We(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,Y)(C)):C===null||We(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),F)}function Y(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||We(C)?Y(C):(e.enter("htmlFlowData"),F(C))}function T(C){return C===45?(e.consume(C),j):F(C)}function z(C){return C===47?(e.consume(C),c="",q):F(C)}function q(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):F(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),q):F(C)}function xe(C){return C===93?(e.consume(C),j):F(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):F(C)}function D(C){return C===null||We(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return We(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Go,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),W):j===63?(e.consume(j),H):xn(j)?(e.consume(j),he):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),O):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):We(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):We(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function O(j){return j===null||j===62?T(j):We(j)?(c=O,z(j)):(e.consume(j),O)}function H(j){return j===null?i(j):j===63?(e.consume(j),A):We(j)?(c=H,z(j)):(e.consume(j),H)}function A(j){return j===62?T(j):H(j)}function W(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||on(j)?(e.consume(j),R):re(j)}function re(j){return We(j)?(c=re,z(j)):gt(j)?(e.consume(j),re):T(j)}function he(j){return j===45||on(j)?(e.consume(j),he):j===47||j===62||Wt(j)?be(j):i(j)}function be(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):We(j)?(c=be,z(j)):gt(j)?(e.consume(j),be):T(j)}function B(j){return j===45||j===46||j===58||j===95||on(j)?(e.consume(j),B):se(j)}function se(j){return j===61?(e.consume(j),F):We(j)?(c=se,z(j)):gt(j)?(e.consume(j),se):be(j)}function F(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,Y):We(j)?(c=F,z(j)):gt(j)?(e.consume(j),F):(e.consume(j),V)}function Y(j){return j===a?(e.consume(j),a=void 0,U):j===null?i(j):We(j)?(c=Y,z(j)):(e.consume(j),Y)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||Wt(j)?be(j):(e.consume(j),V)}function U(j){return j===47||j===62||Wt(j)?be(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),q}function q(j){return gt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||We(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),gt(f)?yt(e,h,"whitespace")(f):h(f))}}const An={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Go,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return gt(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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Go,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!gt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(An,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(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!gt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),gt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||We(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Go,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++inew Set(it).add(K))}},he.term.onData(st=>{He.readyState===WebSocket.OPEN&&He.send(st)}),he.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,he)=>{if(!S.current||Oi.has(K))return;const{resume:ge=!1,autoConnect:De=!0}=he??{},ze=document.createElement("div");ze.style.width="100%",ze.style.height="100%",ze.style.display="none",ze.style.paddingLeft="10px",ze.style.boxSizing="border-box",S.current.appendChild(ze);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),we=new WE,He=new XE;Fe.loadAddon(we),Fe.loadAddon(He),Fe.open(ze);const tt={term:Fe,fit:we,serialize:He,ws:null,container:ze,observer:null,connected:!1},st=new ResizeObserver(()=>{var Nt;const{width:it}=ze.getBoundingClientRect();if(!(it<50))try{we.fit(),((Nt=tt.ws)==null?void 0:Nt.readyState)===WebSocket.OPEN&&tt.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});st.observe(ze),tt.observer=st,Oi.set(K,tt),E(it=>[...it,K]);try{const it=await rN(K);if(it){const Nt=lv(it);Fe.write(Nt),Nt!==it&&tl(K,Nt).catch(()=>{})}}catch{}De?xe(K,tt,ge):I(it=>new Set(it).add(K)),setTimeout(()=>H(tt),50)},[xe,H]),D=w.useCallback(async(K,he)=>{const ge=Oi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,he))},[xe]),X=w.useCallback(K=>{const he=Oi.get(K);if(he){try{const ge=he.serialize.serialize();tl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Oi.delete(K),E(ge=>ge.filter(De=>De!==K)),I(ge=>{const De=new Set(ge);return De.delete(K),De}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const he=Oi.get(K);he&&(((ge=he.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Oi.delete(K),E(De=>De.filter(ze=>ze!==K)),I(De=>{const ze=new Set(De);return ze.delete(K),ze}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,he,ge)=>{const De=Oi.get(K);if(!De||Oi.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,...ge??{}})})).ok)return!1;Oi.delete(K),Oi.set(he,De);try{const Fe=De.serialize.serialize();await mf(K),await tl(he,Fe)}catch{}return E(Fe=>Fe.map(we=>we===K?he:we)),I(Fe=>{if(!Fe.has(K))return Fe;const we=new Set(Fe);return we.delete(K),we.add(he),we}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),V.current(he,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if($){T(null);return}if(G){T(null);return}Oi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Oi.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!he}),T(t)}}).catch(()=>{Oi.has(t)||(j(t),T(t))})}},[t,j,T,$,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,ge]of Oi)if(ge.connected)try{const De=ge.serialize.serialize();tl(he,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of Oi){try{const ge=he.serialize.serialize();tl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Oi.clear()},[]);const ae=t?O.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>re(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!$&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),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:ue?"Copied!":"Copy"})]})]})]})}),G&&!$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){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:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>re(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;re(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Wo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Wo.prototype.normal={};Wo.prototype.property={};Wo.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Wo(i,s,t)}function Cp(e){return e.toLowerCase()}class Tn{constructor(t,i){this.attribute=i,this.property=t}}Tn.prototype.attribute="";Tn.prototype.booleanish=!1;Tn.prototype.boolean=!1;Tn.prototype.commaOrSpaceSeparated=!1;Tn.prototype.commaSeparated=!1;Tn.prototype.defined=!1;Tn.prototype.mustUseProperty=!1;Tn.prototype.number=!1;Tn.prototype.overloadedBoolean=!1;Tn.prototype.property="";Tn.prototype.spaceSeparated=!1;Tn.prototype.space=void 0;let dN=0;const lt=ya(),ji=ya(),kp=ya(),Se=ya(),Zt=ya(),ll=ya(),qn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:ji,commaOrSpaceSeparated:qn,commaSeparated:ll,number:Se,overloadedBoolean:kp,spaceSeparated:Zt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Tn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var il={},xf,pv;function wN(){if(pv)return xf;pv=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=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var O=1,I=1;function A(V){var H=V.match(t);H&&(O+=H.length);var T=V.lastIndexOf(p);I=~T?V.length-T:I+V.length}function q(){var V={line:O,column:I};return function(H){return H.position=new R(V),ye(),H}}function R(V){this.start=V,this.end={line:O,column:I},this.source=E.source}R.prototype.content=M;function re(V){var H=new Error(E.source+":"+O+":"+I+": "+V);if(H.reason=V,H.filename=E.source,H.line=O,H.column=I,H.source=M,!E.silent)throw H}function ue(V){var H=V.exec(M);if(H){var T=H[0];return A(T),M=M.slice(T.length),H}}function ye(){ue(i)}function B(V){var H;for(V=V||[];H=se();)H!==!1&&V.push(H);return V}function se(){var V=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var H=2;x!=M.charAt(H)&&(_!=M.charAt(H)||f!=M.charAt(H+1));)++H;if(H+=2,x===M.charAt(H-1))return re("End of comment missing");var T=M.slice(2,H-2);return I+=2,A(T),M=M.slice(H),I+=2,V({type:b,comment:T})}}function $(){var V=q(),H=ue(s);if(H){if(se(),!ue(a))return re("property missing ':'");var T=ue(o),z=V({type:v,property:N(H[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return ue(c),z}}function G(){var V=[];B(V);for(var H;H=$();)H!==!1&&(V.push(H),B(V));return V}return ye(),G()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return il;mv=1;var e=il&&il.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(il,"__esModule",{value:!0}),il.default=i;const t=e(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return il}var xo={},gv;function kN(){if(gv)return xo;gv=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return xo.camelCase=p,xo}var _o,xv;function EN(){if(xv)return _o;xv=1;var e=_o&&_o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,_o=s,_o}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(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 L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ao(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class hn 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=Ao(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}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}zo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);zo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 zo(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 zo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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?(Wn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(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 xn=Ws(/[A-Za-z]/),un=Ws(/[\dA-Za-z]/),JN=Ws(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=Ws(/\d/),e5=Ws(/[\dA-Fa-f]/),t5=Ws(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function Ft(e){return e!==null&&(e<0||e===32)}function mt(e){return e===-2||e===-1||e===32}const Fu=Ws(new RegExp("\\p{P}|\\p{S}","u")),ba=Ws(/\s/);function Ws(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function gl(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 yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return mt(p)?(e.enter(i),h(p)):t(p)}function h(p){return mt(p)&&o++c))return;const re=t.events.length;let ue=re,ye,B;for(;ue--;)if(t.events[ue][0]==="exit"&&t.events[ue][1].type==="chunkFlow"){if(ye){B=t.events[ue][1].end;break}ye=!0}for(E(s),R=re;RI;){const q=i[A];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function O(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function hl(e){if(e===null||Ft(e)||ba(e))return 1;if(Fu(e))return 2}function qu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=sr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=sr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=sr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=sr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=sr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Wn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&mt(R)?yt(e,O,"linePrefix",o+1)(R):O(R)}function O(R){return R===null||Ye(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),O(R)):(e.consume(R),I)}function A(R){return e.exit("codeFenced"),t(R)}function q(R,re,ue){let ye=0;return B;function B(H){return R.enter("lineEnding"),R.consume(H),R.exit("lineEnding"),se}function se(H){return R.enter("codeFencedFence"),mt(H)?yt(R,$,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):$(H)}function $(H){return H===h?(R.enter("codeFencedFenceSequence"),G(H)):ue(H)}function G(H){return H===h?(ye++,R.consume(H),G):ye>=c?(R.exit("codeFencedFenceSequence"),mt(H)?yt(R,V,"whitespace")(H):V(H)):ue(H)}function V(H){return H===null||Ye(H)?(R.exit("codeFencedFence"),re(H)):ue(H)}}}function _5(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 bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(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):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&bo(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),bo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bo(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Mu(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(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):Ye(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||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!mt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ro(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):mt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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)?Ro(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return mt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return Ft(h)?Ro(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return mt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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"},Wn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(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||Ye(_)?(e.exit("atxHeading"),t(_)):mt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Ft(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:$:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||Ft(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):$(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):$(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?O(C):I(C))}return C===45||un(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:$):i(C)}function O(C){return mt(C)?(e.consume(C),O):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):mt(C)?(e.consume(C),I):B(C)}function A(C){return C===45||C===46||C===58||C===95||un(C)?(e.consume(C),A):q(C)}function q(C){return C===61?(e.consume(C),R):mt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,re):mt(C)?(e.consume(C),R):ue(C)}function re(C){return C===p?(e.consume(C),p=null,ye):C===null||Ye(C)?i(C):(e.consume(C),re)}function ue(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),ue)}function ye(C){return C===47||C===62||mt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),se):i(C)}function se(C){return C===null||Ye(C)?$(C):mt(C)?(e.consume(C),se):i(C)}function $(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),$)}function G(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),H}function H(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),$(C))}function T(C){return C===45?(e.consume(C),j):$(C)}function z(C){return C===47?(e.consume(C),c="",F):$(C)}function F(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):$(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),F):$(C)}function xe(C){return C===93?(e.consume(C),j):$(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):$(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Go,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),q):j===63?(e.consume(j),I):xn(j)?(e.consume(j),ue):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),O):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):Ye(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):Ye(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function O(j){return j===null||j===62?T(j):Ye(j)?(c=O,z(j)):(e.consume(j),O)}function I(j){return j===null?i(j):j===63?(e.consume(j),A):Ye(j)?(c=I,z(j)):(e.consume(j),I)}function A(j){return j===62?T(j):I(j)}function q(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||un(j)?(e.consume(j),R):re(j)}function re(j){return Ye(j)?(c=re,z(j)):mt(j)?(e.consume(j),re):T(j)}function ue(j){return j===45||un(j)?(e.consume(j),ue):j===47||j===62||Ft(j)?ye(j):i(j)}function ye(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):Ye(j)?(c=ye,z(j)):mt(j)?(e.consume(j),ye):T(j)}function B(j){return j===45||j===46||j===58||j===95||un(j)?(e.consume(j),B):se(j)}function se(j){return j===61?(e.consume(j),$):Ye(j)?(c=se,z(j)):mt(j)?(e.consume(j),se):ye(j)}function $(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,G):Ye(j)?(c=$,z(j)):mt(j)?(e.consume(j),$):(e.consume(j),V)}function G(j){return j===a?(e.consume(j),a=void 0,H):j===null?i(j):Ye(j)?(c=G,z(j)):(e.consume(j),G)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||Ft(j)?ye(j):(e.consume(j),V)}function H(j){return j===47||j===62||Ft(j)?ye(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),F}function F(j){return mt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),mt(f)?yt(e,h,"whitespace")(f):h(f))}}const jn={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Go,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return mt(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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Go,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!mt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(jn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(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!mt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),mt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Go,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++i0){const Yt=Be.tokenStack[Be.tokenStack.length-1];(Yt[1]||Av).call(Be,void 0,Yt[0])}for(_e.position={start:Ps(te.length>0?te[0][1].start:{line:1,column:1,offset:0}),end:Ps(te.length>0?te[te.length-2][1].end:{line:1,column:1,offset:0})},Ke=-1;++Ke0){const Wt=Me.tokenStack[Me.tokenStack.length-1];(Wt[1]||Av).call(Me,void 0,Wt[0])}for(be.position={start:Is(ee.length>0?ee[0][1].start:{line:1,column:1,offset:0}),end:Is(ee.length>0?ee[ee.length-2][1].end:{line:1,column:1,offset:0})},Xe=-1;++Xe0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=xl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:xl(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 aT(e,t){const i={src:xl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:xl(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 cT(e,t){const i={href:xl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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(;++h0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=gl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:gl(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 aT(e,t){const i={src:gl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:gl(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 cT(e,t){const i={href:gl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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 dT(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=nm(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Do=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 Wu:case iS:return i(c,a);case Do:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),rl="",{toString:CT}={},{keys:kT}=Object,vo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Do,rl];case"Object":return[Bu,rl];case"Date":return[um,rl];case"RegExp":return[hm,rl];case"Map":return[dm,rl];case"Set":return[fm,rl];case"DataView":return[Do,i]}return i.includes("Array")?[Do,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(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]=vo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Do:{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 Bu:{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 kT(c))(e||!cu(vo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(vo(b))||cu(vo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(vo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Po=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let O=typeof i=="string"?i:i(p,v);typeof O=="string"&&(O={type:"text",value:O}),S.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(O)?O:[O]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const O=M.children[M.children.length-1];O&&O.type==="text"?O.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Po(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`});const f={type:"element",tagName:"li",properties:o,children:c};return e.patch(t,f),e.applyData(t,f)}function hT(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const i=e.children;let s=-1;for(;!t&&++s1}function dT(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=nm(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Do=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 Wu:case iS:return i(c,a);case Do:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),nl="",{toString:CT}={},{keys:kT}=Object,vo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Do,nl];case"Object":return[Bu,nl];case"Date":return[um,nl];case"RegExp":return[hm,nl];case"Map":return[dm,nl];case"Set":return[fm,nl];case"DataView":return[Do,i]}return i.includes("Array")?[Do,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(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]=vo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Do:{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 Bu:{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 kT(c))(e||!cu(vo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(vo(b))||cu(vo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(vo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Po=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let O=typeof i=="string"?i:i(p,v);typeof O=="string"&&(O={type:"text",value:O}),S.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(O)?O:[O]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const O=M.children[M.children.length-1];O&&O.type==="text"?O.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Po(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 Gu=(function(e){if(e==null)return MT;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?AT(e):RT(e);if(typeof e=="string")return DT(e);throw new Error("Expected function, string, or object as test")});function AT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` `}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var yf,Hv;function WT(){if(Hv)return yf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,O=!1;for(typeof N=="boolean"&&(O=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Yo(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 XT(e){if(Yo(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 ZT(e){Yo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 Yo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&O.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?O.push(...R):R&&O.push(R),S=A+H[0].length,E=!0),!b.global)break;H=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=H)}N.push(O)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=O),v[x]=O),b[x]=H}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,O=!1;for(typeof N=="boolean"&&(O=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Yo(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 XT(e){if(Yo(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 ZT(e){Yo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 Yo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&O.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?O.push(...R):R&&O.push(R),S=A+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(O)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=O),v[x]=O),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(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 oR(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 cR(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 uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=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),f(),_}function hR(e,t,i){return(i?"":" ")+e}function gm(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 dR(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Io(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=dl(e),a=dl(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Io(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=hl(e),a=hl(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` `,after:` `});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 f=i.containerPhrasing(e,{before:"# ",after:` `,...o.current()});return/^[\t ]/.test(f)&&(f=Io(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function xm(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 wR(e){const t=xm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):xm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Df,tableHeader:Df,tableRow:Df}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),O=f([E]);return O.slice(0,O.indexOf(` -`))}function p(v,S,N,M){const E=N.enter("tableCell"),O=N.enter("phrasing"),H=N.containerPhrasing(v,{...M,before:o,after:o});return O(),E(),H}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const O=[],H=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=dr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||Wt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(dr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Wt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||Wt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=dr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Wt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Go,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=dl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[se][1].type;if(V==="lineEnding"||V==="linePrefix")se--;else break}const F=se>-1?s.events[se][1].type:null,Y=F==="tableHead"||F==="tableRow"?R:p;return Y===R&&s.parser.lazy[s.now().line]?i(B):Y(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):We(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):gt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||Wt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,gt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):W(B)}function N(B){return gt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||We(B)?A(B):W(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),O(B)):W(B)}function O(B){return B===45?(e.consume(B),O):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),H):(e.exit("tableDelimiterFiller"),H(B))}function H(B){return gt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||We(B)?!c||a!==o?W(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):W(B)}function W(B){return i(B)}function R(B){return e.enter("tableRow"),re(B)}function re(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),re):B===null||We(B)?(e.exit("tableRow"),t(B)):gt(B)?yt(e,re,"whitespace")(B):(e.enter("data"),he(B))}function he(B){return B===null||B===124||Wt(B)?(e.exit("data"),re(B)):(e.consume(B),B===92?be:he)}function be(B){return B===92||B===124?(e.consume(B),he):he(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},sl(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=sl(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 sl(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Wt(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 We(p)?t(p):gt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],fl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["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"]},Hs={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...fl,...t}:fl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Vo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Vo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Hs.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const cl=["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"],ns=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(cl.map(e=>[IS(e),e])),P3={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 Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 No(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,O=Math.max(1,_-E),H=a.fontWeight??400,A=iy((re,he)=>e(re,he,H),t,f,N),W=A.length*N*o,R=A.every(re=>e(re,N,H)<=f+.5);return{lines:A,ok:W<=O&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function ul(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=ul(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=ul(t.lineHeightFactor,.9,2),c=ul(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 Vu(e){if(!e||typeof e!="object")return;const t=e,i=ul(t.paddingX,0,.25),s=ul(t.paddingY,0,.25),a=ul(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 jo(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(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 $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:O,half:H}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:O-H,y:E},base2:{x:O+H,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 du=.05;function Wi(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Wi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Wi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Wi(t.x)&&Wi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Wi(b.x)&&Wi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Wi(t.x)&&Wi(t.y)&&Wi(t.width)&&Wi(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=vm(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=Vu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Wi(e==null?void 0:e.x)&&Wi(e==null?void 0:e.y)&&Wi(e==null?void 0:e.width)&&Wi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 yo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(O=>!_[O]),v=O=>s.needClean>0?yo(O,s.needClean):"no image cuts",S={plan:yo(s.total,s.total),clean:v(s.withClean),letter:yo(s.withText,s.total),export:yo(s.exported,s.total),upload:yo(s.uploaded,s.total),publish:null},N=x.map((O,H)=>({key:O,label:cD[O],status:b===-1||HVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Cm=[{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:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(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 ll(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ll(e.current)}function km(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Tn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Yt,fi,Rt,St,Ht,nt,Xt;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let $=!1;return Y(!1),(async()=>{try{const{ensureFontsReady:we}=await uy(async()=>{const{ensureFontsReady:Ee}=await import("./export-cut-m_bbvXgX.js");return{ensureFontsReady:Ee}},[]);await we([b.family,v.family])}catch{}$||Y(!0)})(),()=>{$=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),O=E.invalid.length,[H,A]=w.useState(!1),W=O===0&&E.changed&&E.overlays.length>0,[R,re]=w.useState(()=>E.overlays),[he,be]=w.useState(()=>ll(E.overlays)),B=w.useRef(null),se=w.useCallback($=>(we,Ee,Ae=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ye=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ye?(Ye.font=`${Ae} ${Ee}px ${$}`,Ye.measureText(we).width):we.length*Ee*.5},[]),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,z]=w.useState(!1),[q,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),de=w.useRef(null),ge=w.useCallback(()=>{const $=oe.current;if(!$)return;const we=$.clientWidth,Ee=$.clientHeight;let Ae,Ye;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ae=At.width,Ye=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ae=At.naturalWidth,Ye=At.naturalHeight}if(!we||!Ee)return;const Ue=Math.min(we/Ae,Ee/Ye),ut=Ae*Ue,vt=Ye*Ue;ae({x:(we-ut)/2,y:(Ee-vt)/2,width:ut,height:vt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const $=oe.current;if(!$)return;const we=new ResizeObserver(()=>ge());return we.observe($),()=>we.disconnect()},[ge]);const Me=w.useCallback($=>{const we=WS($.type,$.x,$.y),Ee=we.width,Ae=Math.max(.08,1-$.y);if(!$.text||!F||Z.width<=0)return we;const Ye=$.type==="sfx"?N:S,Ue=Tn(Ee,Z.width);let ut=$.type==="sfx"?.08:.12;for(let vt=0;vt<24;vt++){const At=Math.min(ut,Ae),Bt=Tn(At,Z.height);if(!No(se(Ye),$.text,Ue,Bt,jo({...$},Z.height||300,Ue,Bt)).overflow||At>=Ae)return{width:Ee,height:At};ut+=.03}return{width:Ee,height:Math.min(ut,Ae)}},[F,Z,se,S,N]),Pe=w.useCallback($=>{const we=Lp($,.1+Math.random()*.3,.1+Math.random()*.3),Ee={...we,...Me(we)};re(Ae=>[...Ae,Ee]),U(Ee.id)},[Me]),Fe=w.useCallback($=>{const Ee={...Lp($.type,.1+Math.random()*.3,.1+Math.random()*.3),text:$.text,...$.type==="speech"&&$.speaker?{speaker:$.speaker}:{}},Ae={...Ee,...Me(Ee)};re(Ye=>[...Ye,Ae]),U(Ae.id)},[Me]),Se=w.useCallback(($,we)=>{re(Ee=>Ee.map(Ae=>Ae.id===$?{...Ae,...we}:Ae))},[]),He=w.useCallback($=>{var ut;const we=Z.height||300,Ee=Z.width>0?Tn($.width,Z.width):200,Ae=Z.height>0?Tn($.height,Z.height):100,Ye=$.type==="sfx"?N:S,Ue=No(se(Ye),$.text,Ee,Ae,jo({...$,textStyle:void 0},we,Ee,Ae));Se($.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,we),fontWeight:((ut=$.textStyle)==null?void 0:ut.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,se,Se]),Je=w.useCallback($=>{re(we=>we.filter(Ee=>Ee.id!==$)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),et=w.useCallback(($,we)=>{$.stopPropagation(),U(we),z(!1)},[]),jt=w.useCallback(($,we,Ee)=>{$.stopPropagation(),$.preventDefault();const Ae=R.find(Ye=>Ye.id===we);Ae&&(U(we),de.current={id:we,mode:Ee,startX:$.clientX,startY:$.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const $=Ee=>{const Ae=de.current;if(!Ae||Z.width===0)return;const Ye=dy(Ee.clientX-Ae.startX,Z.width),Ue=dy(Ee.clientY-Ae.startY,Z.height);if(Ae.mode==="move"){const ut=pu(Ae.origX+Ye,0,1-Ae.origW),vt=pu(Ae.origY+Ue,0,1-Ae.origH);Se(Ae.id,{x:ut,y:vt})}else{const ut=pu(Ae.origW+Ye,py,1-Ae.origX),vt=pu(Ae.origH+Ue,py,1-Ae.origY);Se(Ae.id,{width:ut,height:vt})}},we=()=>{de.current=null};return window.addEventListener("mousemove",$),window.addEventListener("mouseup",we),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",we)}},[Z,Se]);const Oe=w.useCallback(async()=>{var $;C(null);try{const we=ll(R),Ee=(($=t.aiDraft)==null?void 0:$.status)==="generated"&&we!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ee??null),f&&a()}catch(we){C(we instanceof Error?we.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(O>0&&!H){const $=O;D(`${$} overlay${$===1?"":"s"} from the cut plan ${$===1?"has":"have"} no usable position and cannot be exported — re-place ${$===1?"it":"them"} or discard ${$===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:$,ensureFontsReady:we}=await uy(async()=>{const{exportCut:Vt,ensureFontsReady:rn}=await import("./export-cut-m_bbvXgX.js");return{exportCut:Vt,ensureFontsReady:rn}},[]),Ee=R.some(Vt=>Vt.type==="sfx"),Ae=[b.family,...Ee?[v.family]:[]],{ready:Ye,missing:Ue}=await we(Ae);if(!Ye){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const ut=M.url,vt=await $(ut,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=vt.type==="image/webp"?"webp":"jpg";At.append("file",vt,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)be(ll(R)),o==null||o();else{const Vt=await Ut.json();D(Vt.error||"Export failed")}}catch($){D($ instanceof Error?$.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,O,H]),je=R.find($=>$.id===V),Gt=w.useMemo(()=>X3(R),[R]),yi=w.useRef(t.id);w.useEffect(()=>{yi.current!==t.id&&(yi.current=t.id,be(ll(E.overlays)))},[t.id,E.overlays]);const kt=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:he,current:R}),Xe=w.useMemo(()=>SD({...t,overlays:R},{staleExport:kt}),[t,R,kt]),te=w.useMemo(()=>km(t),[t]),_e=w.useMemo(()=>{const $={};for(const we of R){const Ee=F3(we);let Ae=!1;if(F&&Z.width>0&&we.text){const Ye=we.type==="sfx"?N:S,Ue=Tn(we.width,Z.width),ut=Tn(we.height,Z.height);Ae=No(se(Ye),we.text,Ue,ut,jo(we,Z.height||300,Ue,ut)).overflow}(Ee||Ae)&&($[we.id]={outOfBounds:Ee,overflow:Ae})}return $},[R,F,Z,se,S,N]),Be=Object.keys(_e).length,$e=t.kind==="text",Ke=!t.cleanImagePath;return!$e&&Ke&&R.length===0&&!t.narration&&!((Yt=t.dialogue)!=null&&Yt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Pe("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"}),d.jsx("button",{onClick:()=>Pe("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"}),d.jsx("button",{onClick:()=>Pe("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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:q,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:q?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Oe()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),O>0&&!H?d.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:[d.jsxs("span",{children:[O," overlay",O===1?"":"s"," ","from the cut plan ",O===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",O===1?"it":"them",", or"]}),d.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 ",O," unplaceable overlay",O===1?"":"s"]})]}):O>0?d.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 ",O," unplaceable overlay",O===1?"":"s"," — the export will not include"," ",O===1?"it":"them","."]}):W?d.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,Gt.length>0&&d.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,": ",Gt.length," bubble"," ",Gt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Gt.map($=>`#${$.indexA+1} ${Lf(R[$.indexA])} ↔ #${$.indexB+1} ${Lf(R[$.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",Xe.hasCleanImage],["script-text","Script text",Xe.hasScriptText],["bubbles",`Bubbles placed${Xe.bubblesPlaced?` (${Xe.bubblesPlaced})`:""}`,Xe.bubblesPlaced>0],["exported","Final exported",Xe.exported],["uploaded","Uploaded",Xe.uploaded]].map(([$,we,Ee])=>d.jsxs("span",{"data-testid":`lettering-check-${$}`,"data-done":Ee?"true":"false",className:`flex items-center gap-1 ${Ee?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ee?"✓":"○"}),we]},$))}),kt&&d.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."}),Be>0&&d.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:[Be," bubble",Be===1?"":"s"," may not export cleanly:"," ",Object.entries(_e).map(([$,we])=>{const Ee=R.findIndex(Ye=>Ye.id===$),Ae=[we.outOfBounds?"outside image":null,we.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ee+1} ${Lf(R[Ee])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:$=>{if($&&Z.width===0){const we=$.getBoundingClientRect();we.width>0&&ae({x:0,y:0,width:we.width,height:we.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map($=>{if($.type!=="speech")return null;const we=Z.x+Tn($.x,Z.width),Ee=Z.y+Tn($.y,Z.height),Ae=Tn($.width,Z.width),Ye=Tn($.height,Z.height),Ue=$S($,Ae,Ye),ut=$.tailAnchor?ym(we,Ee,Ae,Ye,$.tailAnchor,Ue):null,vt=Math.max(1.5,Z.height*.004),At=$.id===V;return d.jsx("path",{"data-testid":`balloon-${$.id}`,d:qS(we,Ee,Ae,Ye,ut,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?vt+.5:vt,strokeLinejoin:"round"},$.id)})}),Z.width>0&&R.map($=>{const we=Z.x+Tn($.x,Z.width),Ee=Z.y+Tn($.y,Z.height),Ae=Tn($.width,Z.width),Ye=Tn($.height,Z.height),Ue=$.id===V,ut=$.type==="speech",vt=$.type==="narration",At=!!_e[$.id];return d.jsxs("div",{"data-testid":`overlay-${$.id}`,"data-warning":At?"true":"false",onClick:Bt=>et(Bt,$.id),onMouseDown:Bt=>jt(Bt,$.id,"move"),className:`absolute rounded cursor-move select-none ${ut?"":`border-2 ${kD[$.type]}`} ${vt?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!ut?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:we,top:Ee,width:Ae,height:Ye},children:[(()=>{var rn,ri;const Bt=$.type==="sfx"?N:S;if(!$.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[$.type]});const Ut=$.type!=="sfx"&&!!$.speaker;if(!F)return d.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(Ye*.05,16)),fontWeight:((rn=$.textStyle)==null?void 0:rn.fontWeight)??400},"data-testid":`overlay-text-${$.id}`,"data-fonts-ready":"false",children:Ut?`${$.speaker}: ${$.text}`:$.text});const Vt=No(se(Bt),$.text,Ae,Ye,jo($,Z.height,Ae,Ye));return d.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-${$.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Vt.speakerFontSize,lineHeight:1.2},children:$.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Vt.fontSize,lineHeight:`${Vt.lineHeight}px`,fontWeight:((ri=$.textStyle)==null?void 0:ri.fontWeight)??400},children:Vt.lines.map((vn,Wn)=>d.jsx("span",{className:"block",children:vn},Wn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),jt(Bt,$.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${$.id}`})]},$.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((fi=t.aiDraft)==null?void 0:fi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),te.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:te.map($=>d.jsxs("button",{onClick:()=>Fe($),"data-testid":`script-insert-${$.key}`,title:`Add ${$.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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[$.type]]})," ",d.jsxs("span",{className:"text-muted",children:[$.speaker?`${$.speaker}: `:"",$.text.length>32?`${$.text.slice(0,32)}…`:$.text]})]},$.key))})]}),je?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[je.type]}),je.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:je.speaker||"",onChange:$=>Se(je.id,{speaker:$.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:je.text,onChange:$=>Se(je.id,{text:$.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"})]}),d.jsx("button",{onClick:()=>Se(je.id,Me(je)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=je.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>Se(je.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"}):d.jsx("button",{type:"button",onClick:()=>He(je),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"})]}),((St=je.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((je.textStyle.fontScale??.032)*100).toFixed(1),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(je.textStyle.fontWeight??400),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",fontWeight:$.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(je.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat($.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"})]}),je.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(je.textStyle.speakerScale??.8).toFixed(2),onChange:$=>Se(je.id,{textStyle:{...je.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat($.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),je.type==="speech"&&(()=>{const $=je.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(we=>d.jsx("button",{type:"button",onClick:()=>Se(je.id,{tailAnchor:we.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-${we.key}`,children:we.label},we.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:$.x,onChange:we=>Se(je.id,{tailAnchor:{...$,x:parseFloat(we.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:$.y,onChange:we=>Se(je.id,{tailAnchor:{...$,y:parseFloat(we.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"})]})]})]})})(),je.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Ht=je.bubbleStyle)==null?void 0:Ht.paddingX)??.06)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((nt=je.bubbleStyle)==null?void 0:nt.paddingY)??.08)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat($.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Xt=je.bubbleStyle)==null?void 0:Xt.cornerRadius)??.4)*100).toFixed(0),onChange:$=>Se(je.id,{bubbleStyle:{...je.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat($.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",je.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",je.x.toFixed(3),", y:"," ",je.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",je.width.toFixed(3),", h:"," ",je.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?Je(je.id):z(!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:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[O,H]=w.useState(!1),[A,W]=w.useState(()=>YS(h)??{width:800,height:600}),[R,re]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var se;try{(se=document.fonts)!=null&&se.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||H(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const se=new ResizeObserver(()=>{re({width:B.clientWidth,height:B.clientHeight})});return se.observe(B),()=>se.disconnect()},[]);const he=w.useCallback(B=>(se,F,Y=400)=>E?(E.font=`${Y} ${F}px ${B}`,E.measureText(se).width):se.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const se=B.currentTarget.naturalWidth||A.width,F=B.currentTarget.naturalHeight||A.height;se>0&&F>0&&W({width:se,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const se=B.x*R.width,F=B.y*R.height,Y=B.width*R.width,V=B.height*R.height,U=$S(B,Y,V),T=B.tailAnchor?ym(se,F,Y,V,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(se,F,Y,V,T,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var q;const se=B.x*R.width,F=B.y*R.height,Y=B.width*R.width,V=B.height*R.height,U=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:se,top:F,width:Y,height:V},children:B.text?O?(()=>{var j;const xe=No(he(U),B.text,Y,V,jo(B,R.height,Y,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((q=B.textStyle)==null?void 0:q.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` +`))}function p(v,S,N,M){const E=N.enter("tableCell"),O=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return O(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const O=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=pr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(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?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||Ft(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Ft(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Go,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=hl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[se][1].type;if(V==="lineEnding"||V==="linePrefix")se--;else break}const $=se>-1?s.events[se][1].type:null,G=$==="tableHead"||$==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):mt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||Ft(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,mt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return mt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?A(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),O(B)):q(B)}function O(B){return B===45?(e.consume(B),O):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return mt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),re(B)}function re(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),re):B===null||Ye(B)?(e.exit("tableRow"),t(B)):mt(B)?yt(e,re,"whitespace")(B):(e.enter("data"),ue(B))}function ue(B){return B===null||B===124||Ft(B)?(e.exit("data"),re(B)):(e.consume(B),B===92?ye:ue)}function ye(B){return B===92||B===124?(e.consume(B),ue):ue(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},rl(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=rl(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 rl(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Ye(p)?t(p):mt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],dl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["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"]},Us={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...dl,...t}:dl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Vo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Vo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Us.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const ol=["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"],rs=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(ol.map(e=>[IS(e),e])),P3={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 Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 No(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,O=Math.max(1,_-E),I=a.fontWeight??400,A=iy((re,ue)=>e(re,ue,I),t,f,N),q=A.length*N*o,R=A.every(re=>e(re,N,I)<=f+.5);return{lines:A,ok:q<=O&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function cl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=cl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=cl(t.lineHeightFactor,.9,2),c=cl(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 Vu(e){if(!e||typeof e!="object")return;const t=e,i=cl(t.paddingX,0,.25),s=cl(t.paddingY,0,.25),a=cl(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 jo(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(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 $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:O,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:O-I,y:E},base2:{x:O+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 du=.05;function Vi(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Vi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Vi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Vi(t.x)&&Vi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Vi(b.x)&&Vi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Vi(t.x)&&Vi(t.y)&&Vi(t.width)&&Vi(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=vm(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=Vu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Vi(e==null?void 0:e.x)&&Vi(e==null?void 0:e.y)&&Vi(e==null?void 0:e.width)&&Vi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 yo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(O=>!_[O]),v=O=>s.needClean>0?yo(O,s.needClean):"no image cuts",S={plan:yo(s.total,s.total),clean:v(s.withClean),letter:yo(s.withText,s.total),export:yo(s.exported,s.total),upload:yo(s.uploaded,s.total),publish:null},N=x.map((O,I)=>({key:O,label:cD[O],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Cm=[{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:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(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 al(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==al(e.current)}function km(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Nn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,pi,Rt,St,Gt,ot,Ht;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let U=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Ce}=await uy(async()=>{const{ensureFontsReady:Ae}=await import("./export-cut-33MiJugN.js");return{ensureFontsReady:Ae}},[]);await Ce([b.family,v.family])}catch{}U||G(!0)})(),()=>{U=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),O=E.invalid.length,[I,A]=w.useState(!1),q=O===0&&E.changed&&E.overlays.length>0,[R,re]=w.useState(()=>E.overlays),[ue,ye]=w.useState(()=>al(E.overlays)),B=w.useRef(null),se=w.useCallback(U=>(Ce,Ae,Ne=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ge?(Ge.font=`${Ne} ${Ae}px ${U}`,Ge.measureText(Ce).width):Ce.length*Ae*.5},[]),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(!1),[F,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),he=w.useRef(null),ge=w.useCallback(()=>{const U=oe.current;if(!U)return;const Ce=U.clientWidth,Ae=U.clientHeight;let Ne,Ge;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ne=At.width,Ge=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ne=At.naturalWidth,Ge=At.naturalHeight}if(!Ce||!Ae)return;const Ue=Math.min(Ce/Ne,Ae/Ge),dt=Ne*Ue,_t=Ge*Ue;ae({x:(Ce-dt)/2,y:(Ae-_t)/2,width:dt,height:_t})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const U=oe.current;if(!U)return;const Ce=new ResizeObserver(()=>ge());return Ce.observe(U),()=>Ce.disconnect()},[ge]);const De=w.useCallback(U=>{const Ce=WS(U.type,U.x,U.y),Ae=Ce.width,Ne=Math.max(.08,1-U.y);if(!U.text||!$||Z.width<=0)return Ce;const Ge=U.type==="sfx"?N:S,Ue=Nn(Ae,Z.width);let dt=U.type==="sfx"?.08:.12;for(let _t=0;_t<24;_t++){const At=Math.min(dt,Ne),Bt=Nn(At,Z.height);if(!No(se(Ge),U.text,Ue,Bt,jo({...U},Z.height||300,Ue,Bt)).overflow||At>=Ne)return{width:Ae,height:At};dt+=.03}return{width:Ae,height:Math.min(dt,Ne)}},[$,Z,se,S,N]),ze=w.useCallback(U=>{const Ce=Lp(U,.1+Math.random()*.3,.1+Math.random()*.3),Ae={...Ce,...De(Ce)};re(Ne=>[...Ne,Ae]),H(Ae.id)},[De]),Fe=w.useCallback(U=>{const Ae={...Lp(U.type,.1+Math.random()*.3,.1+Math.random()*.3),text:U.text,...U.type==="speech"&&U.speaker?{speaker:U.speaker}:{}},Ne={...Ae,...De(Ae)};re(Ge=>[...Ge,Ne]),H(Ne.id)},[De]),we=w.useCallback((U,Ce)=>{re(Ae=>Ae.map(Ne=>Ne.id===U?{...Ne,...Ce}:Ne))},[]),He=w.useCallback(U=>{var dt;const Ce=Z.height||300,Ae=Z.width>0?Nn(U.width,Z.width):200,Ne=Z.height>0?Nn(U.height,Z.height):100,Ge=U.type==="sfx"?N:S,Ue=No(se(Ge),U.text,Ae,Ne,jo({...U,textStyle:void 0},Ce,Ae,Ne));we(U.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,Ce),fontWeight:((dt=U.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,se,we]),tt=w.useCallback(U=>{re(Ce=>Ce.filter(Ae=>Ae.id!==U)),H(null),z(!1)},[]),st=w.useCallback(()=>{H(null),z(!1)},[]),it=w.useCallback((U,Ce)=>{U.stopPropagation(),H(Ce),z(!1)},[]),Nt=w.useCallback((U,Ce,Ae)=>{U.stopPropagation(),U.preventDefault();const Ne=R.find(Ge=>Ge.id===Ce);Ne&&(H(Ce),he.current={id:Ce,mode:Ae,startX:U.clientX,startY:U.clientY,origX:Ne.x,origY:Ne.y,origW:Ne.width,origH:Ne.height})},[R]);w.useEffect(()=>{const U=Ae=>{const Ne=he.current;if(!Ne||Z.width===0)return;const Ge=dy(Ae.clientX-Ne.startX,Z.width),Ue=dy(Ae.clientY-Ne.startY,Z.height);if(Ne.mode==="move"){const dt=pu(Ne.origX+Ge,0,1-Ne.origW),_t=pu(Ne.origY+Ue,0,1-Ne.origH);we(Ne.id,{x:dt,y:_t})}else{const dt=pu(Ne.origW+Ge,py,1-Ne.origX),_t=pu(Ne.origH+Ue,py,1-Ne.origY);we(Ne.id,{width:dt,height:_t})}},Ce=()=>{he.current=null};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",Ce),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Ce)}},[Z,we]);const Be=w.useCallback(async()=>{var U;C(null);try{const Ce=al(R),Ae=((U=t.aiDraft)==null?void 0:U.status)==="generated"&&Ce!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ae??null),f&&a()}catch(Ce){C(Ce instanceof Error?Ce.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(O>0&&!I){const U=O;D(`${U} overlay${U===1?"":"s"} from the cut plan ${U===1?"has":"have"} no usable position and cannot be exported — re-place ${U===1?"it":"them"} or discard ${U===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:U,ensureFontsReady:Ce}=await uy(async()=>{const{exportCut:Yt,ensureFontsReady:an}=await import("./export-cut-33MiJugN.js");return{exportCut:Yt,ensureFontsReady:an}},[]),Ae=R.some(Yt=>Yt.type==="sfx"),Ne=[b.family,...Ae?[v.family]:[]],{ready:Ge,missing:Ue}=await Ce(Ne);if(!Ge){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const dt=M.url,_t=await U(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=_t.type==="image/webp"?"webp":"jpg";At.append("file",_t,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)ye(al(R)),o==null||o();else{const Yt=await Ut.json();D(Yt.error||"Export failed")}}catch(U){D(U instanceof Error?U.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,O,I]),Te=R.find(U=>U.id===V),qt=w.useMemo(()=>X3(R),[R]),yi=w.useRef(t.id);w.useEffect(()=>{yi.current!==t.id&&(yi.current=t.id,ye(al(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:ue,current:R}),Je=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),ee=w.useMemo(()=>km(t),[t]),be=w.useMemo(()=>{const U={};for(const Ce of R){const Ae=F3(Ce);let Ne=!1;if($&&Z.width>0&&Ce.text){const Ge=Ce.type==="sfx"?N:S,Ue=Nn(Ce.width,Z.width),dt=Nn(Ce.height,Z.height);Ne=No(se(Ge),Ce.text,Ue,dt,jo(Ce,Z.height||300,Ue,dt)).overflow}(Ae||Ne)&&(U[Ce.id]={outOfBounds:Ae,overflow:Ne})}return U},[R,$,Z,se,S,N]),Me=Object.keys(be).length,$e=t.kind==="text",Xe=!t.cleanImagePath;return!$e&&Xe&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:F,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:F?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Be()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),O>0&&!I?d.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:[d.jsxs("span",{children:[O," overlay",O===1?"":"s"," ","from the cut plan ",O===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",O===1?"it":"them",", or"]}),d.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 ",O," unplaceable overlay",O===1?"":"s"]})]}):O>0?d.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 ",O," unplaceable overlay",O===1?"":"s"," — the export will not include"," ",O===1?"it":"them","."]}):q?d.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,qt.length>0&&d.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,": ",qt.length," bubble"," ",qt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",qt.map(U=>`#${U.indexA+1} ${Lf(R[U.indexA])} ↔ #${U.indexB+1} ${Lf(R[U.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",Je.hasCleanImage],["script-text","Script text",Je.hasScriptText],["bubbles",`Bubbles placed${Je.bubblesPlaced?` (${Je.bubblesPlaced})`:""}`,Je.bubblesPlaced>0],["exported","Final exported",Je.exported],["uploaded","Uploaded",Je.uploaded]].map(([U,Ce,Ae])=>d.jsxs("span",{"data-testid":`lettering-check-${U}`,"data-done":Ae?"true":"false",className:`flex items-center gap-1 ${Ae?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ae?"✓":"○"}),Ce]},U))}),Ct&&d.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."}),Me>0&&d.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:[Me," bubble",Me===1?"":"s"," may not export cleanly:"," ",Object.entries(be).map(([U,Ce])=>{const Ae=R.findIndex(Ge=>Ge.id===U),Ne=[Ce.outOfBounds?"outside image":null,Ce.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ae+1} ${Lf(R[Ae])} (${Ne})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:st,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:U=>{if(U&&Z.width===0){const Ce=U.getBoundingClientRect();Ce.width>0&&ae({x:0,y:0,width:Ce.width,height:Ce.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(U=>{if(U.type!=="speech")return null;const Ce=Z.x+Nn(U.x,Z.width),Ae=Z.y+Nn(U.y,Z.height),Ne=Nn(U.width,Z.width),Ge=Nn(U.height,Z.height),Ue=$S(U,Ne,Ge),dt=U.tailAnchor?ym(Ce,Ae,Ne,Ge,U.tailAnchor,Ue):null,_t=Math.max(1.5,Z.height*.004),At=U.id===V;return d.jsx("path",{"data-testid":`balloon-${U.id}`,d:qS(Ce,Ae,Ne,Ge,dt,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?_t+.5:_t,strokeLinejoin:"round"},U.id)})}),Z.width>0&&R.map(U=>{const Ce=Z.x+Nn(U.x,Z.width),Ae=Z.y+Nn(U.y,Z.height),Ne=Nn(U.width,Z.width),Ge=Nn(U.height,Z.height),Ue=U.id===V,dt=U.type==="speech",_t=U.type==="narration",At=!!be[U.id];return d.jsxs("div",{"data-testid":`overlay-${U.id}`,"data-warning":At?"true":"false",onClick:Bt=>it(Bt,U.id),onMouseDown:Bt=>Nt(Bt,U.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[U.type]}`} ${_t?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!dt?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:Ce,top:Ae,width:Ne,height:Ge},children:[(()=>{var an,ai;const Bt=U.type==="sfx"?N:S;if(!U.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[U.type]});const Ut=U.type!=="sfx"&&!!U.speaker;if(!$)return d.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(Ge*.05,16)),fontWeight:((an=U.textStyle)==null?void 0:an.fontWeight)??400},"data-testid":`overlay-text-${U.id}`,"data-fonts-ready":"false",children:Ut?`${U.speaker}: ${U.text}`:U.text});const Yt=No(se(Bt),U.text,Ne,Ge,jo(U,Z.height,Ne,Ge));return d.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-${U.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Yt.speakerFontSize,lineHeight:1.2},children:U.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Yt.fontSize,lineHeight:`${Yt.lineHeight}px`,fontWeight:((ai=U.textStyle)==null?void 0:ai.fontWeight)??400},children:Yt.lines.map((An,Rn)=>d.jsx("span",{className:"block",children:An},Rn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),Nt(Bt,U.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${U.id}`})]},U.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((pi=t.aiDraft)==null?void 0:pi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),ee.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:ee.map(U=>d.jsxs("button",{onClick:()=>Fe(U),"data-testid":`script-insert-${U.key}`,title:`Add ${U.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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[U.type]]})," ",d.jsxs("span",{className:"text-muted",children:[U.speaker?`${U.speaker}: `:"",U.text.length>32?`${U.text.slice(0,32)}…`:U.text]})]},U.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:U=>we(Te.id,{speaker:U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:U=>we(Te.id,{text:U.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"})]}),d.jsx("button",{onClick:()=>we(Te.id,De(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=Te.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>we(Te.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"}):d.jsx("button",{type:"button",onClick:()=>He(Te),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"})]}),((St=Te.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontWeight:U.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(U.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(U.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const U=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Ce=>d.jsx("button",{type:"button",onClick:()=>we(Te.id,{tailAnchor:Ce.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-${Ce.key}`,children:Ce.label},Ce.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:U.x,onChange:Ce=>we(Te.id,{tailAnchor:{...U,x:parseFloat(Ce.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:U.y,onChange:Ce=>we(Te.id,{tailAnchor:{...U,y:parseFloat(Ce.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Gt=Te.bubbleStyle)==null?void 0:Gt.paddingX)??.06)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((ot=Te.bubbleStyle)==null?void 0:ot.paddingY)??.08)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Ht=Te.bubbleStyle)==null?void 0:Ht.cornerRadius)??.4)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(U.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?tt(Te.id):z(!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:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[O,I]=w.useState(!1),[A,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,re]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var se;try{(se=document.fonts)!=null&&se.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const se=new ResizeObserver(()=>{re({width:B.clientWidth,height:B.clientHeight})});return se.observe(B),()=>se.disconnect()},[]);const ue=w.useCallback(B=>(se,$,G=400)=>E?(E.font=`${G} ${$}px ${B}`,E.measureText(se).width):se.length*$*.5,[E]),ye=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const se=B.currentTarget.naturalWidth||A.width,$=B.currentTarget.naturalHeight||A.height;se>0&&$>0&&q({width:se,height:$})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const se=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=$S(B,G,V),T=B.tailAnchor?ym(se,$,G,V,B.tailAnchor,H):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(se,$,G,V,T,H),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var F;const se=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:se,top:$,width:G,height:V},children:B.text?O?(()=>{var j;const xe=No(ue(H),B.text,G,V,jo(B,R.height,G,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:H},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:H,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((F=B.textStyle)==null?void 0:F.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:H},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:ye}):ye}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` `).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(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(` -`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(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 Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const O=await GD(e);E||o(O)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const O=await YD(e,E);await i(O)}catch(O){h(O instanceof Error?O.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(O=>O.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(O=>O.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(O=>O.status!=="done").length,M=p.reduce((O,H)=>O+H.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(O=>d.jsxs("li",{"data-testid":`finish-step-${O.key}`,"data-status":O.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${O.status==="current"?"border-accent/40 bg-accent/10 text-accent":O.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[O.status]}),d.jsx("span",{children:O.label}),O.detail&&d.jsxs("span",{className:"text-muted",children:["· ",O.detail]})]},O.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(O=>d.jsxs("div",{"data-testid":`finish-issue-group-${O.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:O.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:O.lines.map((H,A)=>d.jsx("li",{children:H},A))})]},O.key))})]})]})]})}function tM(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 Mo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:ll(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:gn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Mo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:O,converting:H,rowRef:A}){var Fe,Se;const W=w.useRef(null),[R,re]=w.useState(!1),[he,be]=w.useState(null),[B,se]=w.useState(!1),[F,Y]=w.useState(!1),[V,U]=w.useState(!1),[T,z]=w.useState(!1),q=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await O(e.id,E),z(!1),h())},[E,O,e.id,h]),X=w.useCallback(async He=>{re(!0),be(null);try{let Je=He;if(!n1(He))try{Je=await Ku(He)}catch(Oe){return be(Oe instanceof Error?Oe.message:"Could not import image"),!1}const at=Je.type==="image/jpeg"?"jpg":"webp",et=new FormData;et.append("file",new File([Je],`clean.${at}`,{type:Je.type}));const jt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:et});if(!jt.ok){const Oe=await jt.json();return be(Oe.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{re(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Mo(e),de=(((Se=e.overlays)==null?void 0:Se.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=rM(e),Pe=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Pe?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":de})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||H),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":de}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:T||H,"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:T?"Converting…":"Convert image"})]}),xe&&!j&&d.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:[S.map((He,Je)=>d.jsx("p",{className:"text-[11px] text-error",children:He},Je)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),se(!0),setTimeout(()=>se(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:W,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var at;const Je=(at=He.target.files)==null?void 0:at[0];Je&&X(Je),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=W.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(He=>!He),disabled:R,"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:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.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."}),q==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),Y(!0),setTimeout(()=>Y(!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:F?"Copied!":"Copy Codex task"})]}),q==="missing"&&f&&d.jsx("button",{onClick:_,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"}),he&&d.jsx("p",{className:"text-xs text-error mt-1",children:he})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,Je)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},Je))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var fr,pi,Zt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,O]=w.useState(null),[H,A]=w.useState(null),[W,R]=w.useState(null),[re,he]=w.useState(!1),[be,B]=w.useState([]),[se,F]=w.useState(!1),[Y,V]=w.useState(""),[U,T]=w.useState({markdownReady:!1,published:!1}),[z,q]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,de]=w.useState(null),[ge,Me]=w.useState(!1),[Pe,Fe]=w.useState(new Set),[Se,He]=w.useState(new Map),[Je,at]=w.useState(!1),[et,jt]=w.useState(null),[Oe,ct]=w.useState(!1),[je,Gt]=w.useState(null),yi=w.useRef(new Map),kt=w.useRef(null),Xe=t.replace(/\.md$/,"");w.useEffect(()=>{var Q;c&&kt.current!==c.seq&&(kt.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),Gt(c.cutId)),(Q=S.current)==null||Q.call(S))},[c]),w.useEffect(()=>(p==null||p(W!==null),()=>p==null?void 0:p(!1)),[W,p]),w.useEffect(()=>{var P;if(je==null)return;const Q=yi.current.get(je);Q&&((P=Q.scrollIntoView)==null||P.call(Q,{behavior:"smooth",block:"center"}),Gt(null))},[je,x]);const te=w.useCallback(async()=>{var Q;try{const P=await i(`/api/stories/${e}/cuts/${Xe}`);if(P.status===404){b(null);return}if(!P.ok){const ye=await P.json();O(ye.error||"Failed to load cuts");return}const ce=await P.json();b(ce),O(null);try{const ye=await i(`/api/stories/${e}/${t}`);if(ye.ok){const Te=await ye.json(),De=typeof(Te==null?void 0:Te.content)=="string"?Te.content:"",Le=Array.isArray(ce==null?void 0:ce.cuts)?ce.cuts:[],tt=De.length>0&&KS(De,Le).ready,ft=(Te==null?void 0:Te.status)==="published"||(Te==null?void 0:Te.status)==="published-not-indexed";T({markdownReady:tt,published:ft})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(Q=v.current)==null||Q.call(v)}catch{O("Failed to load cuts")}finally{M(!1)}},[i,e,Xe,t]),_e=w.useCallback(async Q=>!!(await i(`/api/stories/${e}/cuts/${Xe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).ok,[i,e,Xe]),Be=w.useCallback(async()=>{at(!1);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/detect-clean-images`);if(!Q.ok)return;const P=await Q.json();Fe(new Set(Array.isArray(P.detected)?P.detected:[]));const ce=new Map,ye=P.stale;if(Array.isArray(ye))for(const Te of ye){if(typeof(Te==null?void 0:Te.cutId)!="number"||typeof(Te==null?void 0:Te.message)!="string")continue;const De=ce.get(Te.cutId)??[];De.push(Te.message),ce.set(Te.cutId,De)}He(ce),at(!0)}catch{}},[i,e,Xe]),$e=w.useCallback(async()=>{jt(null);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/asset-diagnostics`);if(!Q.ok)return;const P=await Q.json();jt(Array.isArray(P.diagnostics)?P.diagnostics:null)}catch{}},[i,e,Xe]),Ke=w.useCallback(async()=>{ct(!0);try{await Promise.all([te(),Be(),$e()])}finally{ct(!1)}},[te,Be,$e]),Yt=w.useCallback(async(Q,P={})=>{var Te;if(!x)return!1;const ce=x.cuts.find(De=>De.id===Q);if(!ce||!Mo(ce)||(((Te=ce.overlays)==null?void 0:Te.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const ye=hy(ce);if(ye.length===0)return oe(`Cut ${ce.id}: no script lines available to draft.`),!1;de(Q),oe(null);try{const De={...x,cuts:x.cuts.map(tt=>tt.id===Q?{...tt,overlays:ye,aiDraft:_y(ye)}:tt)};return await _e(De)?(oe(`Cut ${ce.id}: AI draft ready`),await te(),P.openEditor&&R(Q),!0):(oe(`Cut ${ce.id}: AI draft failed`),!1)}finally{de(null)}},[x,_e,te]),fi=w.useCallback(async()=>{if(!x)return;const Q=x.cuts.filter(P=>{var ce;return Mo(P)&&(((ce=P.overlays)==null?void 0:ce.length)??0)===0&&!P.finalImagePath&&!P.uploadedCid&&!P.uploadedUrl});if(Q.length===0){oe("No unlettered cuts need an AI draft");return}Me(!0),oe(null);try{const P={...x,cuts:x.cuts.map(ye=>{if(!Q.some(De=>De.id===ye.id))return ye;const Te=hy(ye);return Te.length>0?{...ye,overlays:Te,aiDraft:_y(Te)}:ye})};if(!await _e(P)){oe("AI draft failed");return}oe(`AI draft ready for ${Q.length} cut${Q.length===1?"":"s"}`),await te()}finally{Me(!1)}},[x,_e,te]),Rt=w.useCallback(async()=>{q(!0),oe(null),B([]);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/sync-clean-images`,{method:"POST"}),P=await Q.json().catch(()=>({}));if(!Q.ok)oe(P.error||"Sync failed");else{const ce=Array.isArray(P.synced)?P.synced.length:0,ye=Array.isArray(P.cleared)?P.cleared.length:0,Te=Array.isArray(P.rejected)?P.rejected:[];Te.length>0&&B(Te.map(Le=>`Cut ${Le.cutId}: ${Le.reason}`));const De=[];ce>0&&De.push(`Synced ${ce}`),ye>0&&De.push(`Cleared ${ye} stale path${ye===1?"":"s"}`),oe(De.length>0?De.join(", "):"No new clean images"),await te(),await Be(),await $e()}}catch{oe("Sync failed")}q(!1)},[i,e,Xe,te,Be,$e]),St=w.useCallback(async(Q,P)=>{try{const ce=await i(HS(e,P));if(!ce.ok)return!1;const ye=await ce.blob(),Te=await Ku(new File([ye],"clean.png",{type:ye.type||"image/png"})),De=Te.type==="image/jpeg"?"jpg":"webp",Le=new FormData;return Le.append("file",new File([Te],`clean.${De}`,{type:Te.type})),(await i(`/api/stories/${e}/cuts/${Xe}/upload-clean/${Q}`,{method:"POST",body:Le})).ok}catch{return!1}},[i,e,Xe]),Ht=w.useCallback(async Q=>{X(!0),Z(null);let P=0;const ce=[];for(const ye of Q)await St(ye.cutId,ye.pngPath)?P++:ce.push(ye.cutId);await Ke(),X(!1),Z(ce.length===0?`Converted ${P} image${P===1?"":"s"} to WebP`:`Converted ${P}; ${ce.length} failed (Cut ${ce.join(", ")}) — try Convert image on each`)},[St,Ke]),nt=w.useCallback(async()=>{var Te;if(!x)return;F(!0),V(""),B([]);const Q=x.cuts.filter(De=>De.finalImagePath&&!De.uploadedCid),P=[],ce=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:De})=>V(`Upload limit reached — waiting ${Math.round(De/1e3)}s before continuing…`)});for(let De=0;De{const $t=await i("/api/publish/upload-plot-image",{method:"POST",body:rt});if($t.ok){const{cid:hn,url:ar}=await $t.json();return{ok:!0,status:$t.status,cid:hn,url:ar}}const ti=await $t.json().catch(()=>({}));return{ok:!1,status:$t.status,errorMessage:ti.error}},{...a,onWaiting:({attempt:$t,maxRetries:ti,waitMs:hn})=>V(`Cut ${Le.id} rate-limited — waiting ${Math.round(hn/1e3)}s before retry ${$t}/${ti}...`)});if(!Ct.ok){P.push(`Cut ${Le.id}: upload failed — ${Ct.errorMessage||"unknown"}`);continue}const{cid:Ze,url:Si}=Ct;(await i(`/api/stories/${e}/cuts/${Xe}/set-uploaded/${Le.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Ze,url:Si})})).ok||P.push(`Cut ${Le.id}: failed to record upload`)}catch(tt){P.push(`Cut ${Le.id}: ${tt instanceof Error?tt.message:"failed"}`)}}if(P.length>0){B(P),F(!1),V(""),te();return}V("Preparing episode for publishing…");const ye=await i(`/api/stories/${e}/cuts/${Xe}/generate-markdown`,{method:"POST"});if(ye.ok){const De=await ye.json();((Te=De.warnings)==null?void 0:Te.length)>0&&B(De.warnings)}F(!1),V(""),te()},[x,i,e,Xe,a,te]),Xt=w.useCallback(async()=>{j(!0),oe(null);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/repair-asset-paths`,{method:"POST"}),P=await Q.json().catch(()=>({}));if(!Q.ok)oe(P.error||"Repair failed");else{const ce=Array.isArray(P.cleared)?P.cleared.length:0;oe(ce>0?`Cleared ${ce} stale path${ce===1?"":"s"}`:"No stale paths to clear"),await te(),await Be()}}catch{oe("Repair failed")}j(!1)},[i,e,Xe,te,Be]),[$,we]=w.useState(!1),Ee=w.useCallback(async(Q,P=!0)=>{if(x){we(!0);try{const ce=x.cuts.reduce((tt,ft)=>Math.max(tt,ft.id),0)+1,ye={id:ce,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"},Te=[...x.cuts];Te.splice(Math.max(0,Math.min(Q,Te.length)),0,ye);const De={...x,cuts:Te},Le=await i(`/api/stories/${e}/cuts/${Xe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(De)});if(Le.ok)P?R(ce):A(ce),await te();else{const tt=await Le.json().catch(()=>({}));oe(tt.error||"Could not add text panel")}}catch{oe("Could not add text panel")}we(!1)}},[x,i,e,Xe,te]),Ae=w.useCallback(()=>Ee((x==null?void 0:x.cuts.length)??0,!0),[Ee,x]);if(w.useEffect(()=>{te(),Be(),$e()},[te,Be,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Xe,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:te,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ye=W!==null?x.cuts.find(Q=>Q.id===W):null;if(Ye)return d.jsx(ND,{storyName:e,cut:Ye,plotFile:Xe,language:s,authFetch:i,targetLabel:gn(Ye)?`Between-scene card ${Ye.id}`:`Cut ${String(Ye.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(Q,P)=>{const ce={...x,cuts:x.cuts.map(Te=>Te.id===W?{...Te,overlays:Q,aiDraft:P??Te.aiDraft??null}:Te)};if(!await _e(ce))throw new Error("Failed to save overlays")},onExported:()=>te(),onClose:()=>{R(null),te()}});const Ue=x.cuts.reduce((Q,P)=>{const ce=r1(P);return Q[ce]++,Q},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),ut=x.cuts.filter(Q=>!gn(Q)).length,vt=x.cuts.filter(Q=>GS(Q)).map(Q=>Q.id),At=uD({cuts:x.cuts,published:U.published}),Bt=((fr=At.steps.find(Q=>Q.key==="upload"))==null?void 0:fr.status)==="done",Ut=x.cuts.some(Q=>Q.finalImagePath&&!Q.uploadedCid)||Bt&&!U.markdownReady,Vt=(et??[]).filter(Q=>Q.state==="needs-conversion"&&Q.convertiblePng).map(Q=>({cutId:Q.cutId,pngPath:Q.convertiblePng})),rn=new Map(Vt.map(Q=>[Q.cutId,Q.pngPath])),ri=(et??[]).filter(Q=>Q.state==="needs-conversion"&&Q.issue).map(Q=>Q.issue),vn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((pi=Xe.match(/\d+/))==null?void 0:pi[0])??"0",10)+1}`,Wn=typeof x.title=="string"?x.title:null,un=x.cuts.filter(Q=>!gn(Q)),yn={cuts:x.cuts.length,artwork:un.filter(Q=>Q.cleanImagePath||rn.has(Q.id)).length,converted:un.filter(Q=>Q.cleanImagePath&&/\.(webp|jpe?g)$/i.test(Q.cleanImagePath)).length,lettered:x.cuts.filter(Q=>{var P;return(((P=Q.overlays)==null?void 0:P.length)??0)>0||!!Q.finalImagePath}).length,uploaded:x.cuts.filter(Q=>Q.uploadedCid||Q.uploadedUrl).length},Sn=x.cuts.filter(Q=>{var P;return Mo(Q)&&(((P=Q.overlays)==null?void 0:P.length)??0)===0&&!Q.finalImagePath&&!Q.uploadedCid&&!Q.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:vn}),Wn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Wn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[yn.cuts," cuts · ",yn.artwork," artwork found ·"," ",yn.converted," converted · ",yn.lettered," ","lettered · ",yn.uploaded," uploaded"]})]}),Sn>0&&d.jsx("button",{onClick:fi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${Sn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{he(!0),B([]);try{const Q=await i(`/api/stories/${e}/cuts/${Xe}/generate-markdown`,{method:"POST"});if(Q.ok){const P=await Q.json();B(P.warnings||[])}}catch{}he(!1)},disabled:re,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:re?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:$,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:$?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Ke,disabled:Oe,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:Oe?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Rt,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"}),d.jsx("button",{onClick:nt,disabled:se||!(x!=null&&x.cuts.some(Q=>Q.finalImagePath&&!Q.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:Y||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),vt.length>0&&d.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:[vt.length===1?"Cut":"Cuts"," ",vt.join(", ")," ",vt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",vt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),Je&&ut>0&&Ue.missing===0&&Se.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",ut," clean image",ut===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Vt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Vt.length," PNG image",Vt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Ht(Vt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ri.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ri.map((Q,P)=>d.jsx("li",{children:Q},P))})]})]}),et&&et.length>0&&(()=>{const Q=tM(et),P=et.filter(ce=>ce.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",Q.uploaded," uploaded · ",Q.finalReady," final ·"," ",Q.cleanReady," clean · ",Q.planned," planned",Q.needsConversion>0?` · ${Q.needsConversion} needs conversion`:"",Q.missing>0?` · ${Q.missing} missing`:""]}),P.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:P.map(ce=>d.jsx("li",{children:ce.issue},ce.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:be,onFinish:nt,finishing:se,progressText:Y,canFinish:Ut,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((Q,P)=>{var ce;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:P,beforeLabel:P===0?"Episode opening":`After cut ${(ce=x.cuts[P-1])==null?void 0:ce.id}`,afterLabel:`Before cut ${Q.id}`,disabled:$,onAdd:()=>Ee(P)}),d.jsx(sM,{cut:Q,storyName:e,plotFile:Xe,language:s,expanded:H===Q.id,onToggle:()=>A(H===Q.id?null:Q.id),authFetch:i,onUpdated:()=>{te(),Be(),$e()},onOpenEditor:()=>R(Q.id),detectedLocalClean:Pe.has(Q.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Yt(Q.id,{openEditor:!0})},aiDrafting:K===Q.id,staleMessages:Se.get(Q.id)??[],onRepairStale:Xt,repairing:xe,conversionPng:rn.get(Q.id)??null,onConvert:St,converting:D,rowRef:ye=>{ye?yi.current.set(Q.id,ye):yi.current.delete(Q.id)}})]},Q.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Zt=x.cuts[x.cuts.length-1])==null?void 0:Zt.id}`,afterLabel:"Episode ending",disabled:$,onAdd:()=>Ee(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Ho(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 dM(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 Ip(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 Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...fl,attributes:{...fl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:O=null,onWorkflowActionHandled:H}){const[A,W]=w.useState(null),[R,re]=w.useState(!1),[he,be]=w.useState("preview"),[B,se]=w.useState("publish"),[F,Y]=w.useState("text"),[V,U]=w.useState(null),T=w.useCallback((ne,ke)=>{be("edit"),U(Ne=>({cutId:ne,openEditor:ke,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[z,q]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,de]=w.useState(""),[ge,Me]=w.useState(""),[Pe,Fe]=w.useState(!1),[Se,He]=w.useState(null),[Je,at]=w.useState(0),[et,jt]=w.useState(0),[Oe,ct]=w.useState(null),[je,Gt]=w.useState(null),[yi,kt]=w.useState(null),[Xe,te]=w.useState(0),_e=w.useRef(null),Be=w.useRef(!1),[$e,Ke]=w.useState(!1),[Yt,fi]=w.useState(cl[0]),[Rt,St]=w.useState(ns[0]),[Ht,nt]=w.useState(!1),[Xt,$]=w.useState(null),[we,Ee]=w.useState(null),[Ae,Ye]=w.useState(!1),[Ue,ut]=w.useState(!1),[vt,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Vt,rn]=w.useState(!1),ri=w.useRef(null),vn=w.useRef(null),[Wn,un]=w.useState(!1),[yn,Sn]=w.useState(null),[fr,pi]=w.useState(null),[Zt,Q]=w.useState("unknown"),P=w.useRef(!1),[ce,ye]=w.useState(!1),[Te,De]=w.useState(!1),[Le,tt]=w.useState(null),[ft,wt]=w.useState([]),[rt,Ct]=w.useState(null),Ze=w.useRef(null),Si=w.useRef(null),Br=w.useRef(0),$t=w.useCallback(async()=>{if(!e||!t){W(null);return}const ne=`${e}/${t}`,ke=Si.current!==ne;ke&&(Si.current=ne);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const it=await Ne.json();W(it),(ke||!Be.current)&&(q(it.content??""),ke&&(X(!1),Be.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{re(!0),$t().finally(()=>re(!1))},[$t]),w.useEffect(()=>{if(!e||!t||he==="edit"&&D)return;const ne=setInterval($t,3e3);return()=>clearInterval(ne)},[e,t,$t,he,D]);const[ti,hn]=w.useState(null),ar=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!ar||!e){hn(null);return}let ne=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ke=>ke.ok?ke.json():null).then(ke=>{ne||hn(ke?Op(ke.cuts||[]):null)}).catch(()=>{ne||hn(null)}),()=>{ne=!0}},[ar,e,i]);const os=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!os||!e||!t){He(null),at(0),jt(0),ct(null);return}let ne=!1;const ke=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[Ne,it]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ke}`)]);if(ne)return;if(!it.ok){He("error"),at(0),jt(0),ct(null);return}const Lt=await it.json(),gi=Lt.cuts||[],vr=Ne.ok?(await Ne.json()).content??"":"",xi=XS(vr,gi);ne||(He(xi.stage),at(xi.awaitingCount),jt(xi.totalCuts),ct(Op(gi)),kt(typeof Lt.title=="string"?Lt.title:null))}catch{ne||(He("error"),at(0),jt(0),ct(null))}})(),()=>{ne=!0}},[os,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,Xe]),w.useEffect(()=>{if(!e){Gt(null);return}let ne=!1;return i(`/api/stories/${e}/structure.md`).then(ke=>ke.ok?ke.json():null).then(ke=>{ne||Gt((ke==null?void 0:ke.content)??null)}).catch(()=>{}),()=>{ne=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ne=Cu(p);let ke=ne??"";if(!ne&&je){const it=je.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);it&&(ke=Cu(it[1].replace(/\*+/g,"").trim())??"")}de(ke);let Ne=h&&ns.find(it=>it.toLowerCase()===h.toLowerCase())||"";if(!Ne&&je){const it=je.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);it&&(Ne=ns.find(Lt=>Lt.toLowerCase()===it[1].replace(/\*+/g,"").trim().toLowerCase())||"")}Me(Ne),Fe(f??!1)},[e,p,h,f,je]);const Ws=w.useCallback(ne=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}).catch(()=>{})},[e,i]),Ft=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Be.current=!1,W(ke=>ke&&{...ke,content:z}))}catch{}j(!1)}},[e,t,i,z]),Dn=w.useCallback(async()=>{if(!e||!t)return;const ne=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ne}/generate-markdown`,{method:"POST"})).ok&&(await $t(),te(Ne=>Ne+1))}catch{}},[e,t,i,$t]);w.useEffect(()=>{if(O&&O.seq!==Br.current){switch(Br.current=O.seq,O.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":be("edit"),Y("cuts");break;case"generate-markdown":Dn();break;case"publish":be("preview");break}H==null||H(O.seq)}},[O,x,Dn,H]);const Yi=w.useCallback(ne=>{var it;const ke=(it=ne.target.files)==null?void 0:it[0];if(!ke)return;P.current=!0,Sn(null),pi(null);const Ne=Sy(ke);if(Ne){$(null),Ee(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ri.current&&(ri.current.value=""),Ut(Ne),Q("invalid");return}$(ke),Ee(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(ke))),Ut(null),Q("selected")},[]),Ai=w.useCallback(async ne=>{var Ne;const ke=(Ne=ne.target.files)==null?void 0:Ne[0];if(vn.current&&(vn.current.value=""),!(!ke||!e)){P.current=!0,Sn(null),un(!0),Ut(null);try{let it;try{it=await Ku(ke)}catch(dn){$(null),Ee(Ys=>(Ys&&URL.revokeObjectURL(Ys),null)),Ut(dn instanceof Error?dn.message:"Could not import image");return}const Lt=it.type==="image/jpeg"?"jpg":"webp",gi=new File([it],`cover.${Lt}`,{type:it.type}),vr=new FormData;vr.append("file",gi);const xi=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:vr});if(!xi.ok){const dn=await xi.json().catch(()=>({}));Ut(dn.error||"Cover import failed");return}$(gi),Ee(dn=>(dn&&URL.revokeObjectURL(dn),URL.createObjectURL(gi))),pi(null),Q("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{un(!1)}}},[e,i]),pr=w.useCallback(async ne=>{if(ne.size>1024*1024){tt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ne.type)){tt("Only WebP and JPEG images are accepted");return}De(!0),tt(null);try{const Ne=new FormData;Ne.append("file",ne);const it=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!it.ok){const gi=await it.json();throw new Error(gi.error||"Upload failed")}const Lt=await it.json();wt(gi=>[...gi,{cid:Lt.cid,url:Lt.url}])}catch(Ne){tt(Ne instanceof Error?Ne.message:"Upload failed")}finally{De(!1),Ze.current&&(Ze.current.value="")}},[i]),si=w.useCallback(ne=>{var Ne;const ke=(Ne=ne.target.files)==null?void 0:Ne[0];ke&&pr(ke)},[pr]),Mn=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ye(!0),Ut(null),rn(!1);try{let ne;if(Xt){const Ne=new FormData;Ne.append("file",Xt);const it=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!it.ok){const gi=await it.json();throw new Error(gi.error||"Cover upload failed")}ne=(await it.json()).cid}const ke=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...ne!==void 0&&{coverCid:ne},genre:Yt,language:Rt,isNsfw:Ht})});if(!ke.ok){const Ne=await ke.json();throw new Error(Ne.error||"Update failed")}rn(!0),$(null),ne!==void 0&&(At(!0),Ee(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Q("unknown"),ri.current&&(ri.current.value="")),setTimeout(()=>rn(!1),3e3)}catch(ne){Ut(ne instanceof Error?ne.message:"Update failed")}finally{Ye(!1)}}},[A==null?void 0:A.storylineId,Xt,Yt,Rt,Ht,i]);w.useEffect(()=>{Ke(!1),$(null),Ee(null),Ut(null),rn(!1),ut(!1),ye(!1),wt([]),tt(null),Sn(null),pi(null),Q("unknown"),P.current=!1,Y("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||P.current)return;let ne=!1;return(async()=>{try{const ke=await i(`/api/stories/${e}/cover-asset`);if(ne||!ke.ok)return;const Ne=await ke.json();if(ne)return;if(!(Ne!=null&&Ne.found)){Q("none");return}if(!Ne.valid){pi(Ne.error||"Detected cover asset is invalid and was not used"),Q("invalid");return}const it=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ne||!it.ok)return;const Lt=await it.blob(),gi=new File([Lt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(Sy(gi)||ne||P.current)return;$(gi),Ee(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(gi))),Sn(Ne.path),Q("detected")}catch{}})(),()=>{ne=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;ut(!1);const ne="https://plotlink.xyz";let ke=!1;return fetch(`${ne}/api/storyline/${A.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!ke){if(!Ne){Ut("Could not load current story metadata");return}if(Ne.genre){const it=Cu(Ne.genre);it&&fi(it)}if(Ne.language){const it=ns.find(Lt=>Lt.toLowerCase()===Ne.language.toLowerCase());it&&St(it)}Ne.isNsfw!==void 0&&nt(!!Ne.isNsfw),At(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),ut(!0)}}).catch(()=>{ke||Ut("Could not load current story metadata")}),()=>{ke=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(he!=="edit")return;const ne=ke=>{(ke.metaKey||ke.ctrlKey)&&ke.key==="s"&&(ke.preventDefault(),Ft())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[he,Ft]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const ne=new Date(A.publishedAt).getTime(),ke=300*1e3,Ne=()=>{const Lt=Math.max(0,ke-(Date.now()-ne));oe(Lt)};Ne();const it=setInterval(Ne,1e3);return()=>clearInterval(it)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const Gs=ae!==null&&ae<=0,mr=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Oi=(he==="edit"?z:(A==null?void 0:A.content)??"").length,mi=t==="genesis.md",gr=t?/^plot-\d+\.md$/.test(t):!1,Vi=c==="cartoon"&&gr,Ki=c==="cartoon"&&mi,cs=Ki||Vi,Lr=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",Or=S&&cs,Ko=Ki?ti?ti.total:null:Vi?Se===null?null:et:null,wa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Lr,cutCount:Ko,cutProgress:Ki?ti:null}),_l=(Ki||Vi)&&!Lr,zr=_l?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:je,contentType:"cartoon",episodeTitle:yi}):null,bl=!!zr&&Ho(zr,t),Xo=Vi&&!Lr&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:yi}),xr=Ki&&!Lr?wm((A==null?void 0:A.content)??""):null,Gn=!!xr&&xr.blockers.length>0,vl="w-full max-w-[32rem] rounded-xl border px-3 py-3",yl={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Pr=ne=>{if(!Ki)return null;const ke=cM({hasSelectedCover:!!Xt,invalid:Zt==="invalid",attached:ne});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ke.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${yl[ke.tone]}`,children:ke.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},_r=bl||Xo,Zo=()=>{if(!_l||!zr)return null;const ne=mi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":bl?"true":"false","data-blocked":_r?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ne,":"]})," ",d.jsx("span",{className:_r?"text-error font-medium":"text-foreground",children:zr})]}),bl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",mi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Xo?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",zr,"” 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]})},Sl=()=>xr?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Gn?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),xr.blockers.map((ne,ke)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ne},`b-${ke}`)),xr.warnings.map((ne,ke)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ne},`w-${ke}`))]}):null,us=mi||gr?1e4:null,br=!Lr&&us!==null&&Oi>us,lr=(A==null?void 0:A.content)??"",hs=Lr?{count:0,warnings:[]}:yM(lr),ds=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:_e,value:z,onChange:ne=>{q(ne.target.value),X(!0),Be.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:Ft,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Or&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${br?"text-error font-medium":"text-muted"}`,children:[Oi.toLocaleString(),us!==null?`/${us.toLocaleString()}`:" chars"]}),br&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Oi-us).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>be("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${he==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>be("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${he==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),he==="preview"?Vi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:Se}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Vi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>te(ne=>ne+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Ki?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>Y("text"),className:`px-2 py-0.5 text-[11px] rounded ${F==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>Y("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${F==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:F==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>te(ne=>ne+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):ds})]}):ds,!Or&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:wa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Gs&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),$t())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${mr?` (${mr})`:""}`}),gr&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(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 Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const O=await GD(e);E||o(O)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const O=await YD(e,E);await i(O)}catch(O){h(O instanceof Error?O.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(O=>O.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(O=>O.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(O=>O.status!=="done").length,M=p.reduce((O,I)=>O+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(O=>d.jsxs("li",{"data-testid":`finish-step-${O.key}`,"data-status":O.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${O.status==="current"?"border-accent/40 bg-accent/10 text-accent":O.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[O.status]}),d.jsx("span",{children:O.label}),O.detail&&d.jsxs("span",{className:"text-muted",children:["· ",O.detail]})]},O.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(O=>d.jsxs("div",{"data-testid":`finish-issue-group-${O.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:O.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:O.lines.map((I,A)=>d.jsx("li",{children:I},A))})]},O.key))})]})]})]})}function tM(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 Mo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:al(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:gn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Mo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:O,converting:I,rowRef:A}){var Fe,we;const q=w.useRef(null),[R,re]=w.useState(!1),[ue,ye]=w.useState(null),[B,se]=w.useState(!1),[$,G]=w.useState(!1),[V,H]=w.useState(!1),[T,z]=w.useState(!1),F=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await O(e.id,E),z(!1),h())},[E,O,e.id,h]),X=w.useCallback(async He=>{re(!0),ye(null);try{let tt=He;if(!n1(He))try{tt=await Ku(He)}catch(Be){return ye(Be instanceof Error?Be.message:"Could not import image"),!1}const st=tt.type==="image/jpeg"?"jpg":"webp",it=new FormData;it.append("file",new File([tt],`clean.${st}`,{type:tt.type}));const Nt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:it});if(!Nt.ok){const Be=await Nt.json();return ye(Be.error||"Upload failed"),!1}return h(),!0}catch{return ye("Upload failed"),!1}finally{re(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Mo(e),he=(((we=e.overlays)==null?void 0:we.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,De=rM(e),ze=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:ze?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[De.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:De.label}),d.jsxs("span",{className:"text-muted",children:[" · ",De.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||I),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:T||I,"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:T?"Converting…":"Convert image"})]}),xe&&!j&&d.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:[S.map((He,tt)=>d.jsx("p",{className:"text-[11px] text-error",children:He},tt)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),se(!0),setTimeout(()=>se(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var st;const tt=(st=He.target.files)==null?void 0:st[0];tt&&X(tt),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=q.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>H(He=>!He),disabled:R,"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:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&H(!1)},onClose:()=>H(!1)}),!e.cleanImagePath&&d.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."}),F==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!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:$?"Copied!":"Copy Codex task"})]}),F==="missing"&&f&&d.jsx("button",{onClick:_,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"}),ue&&d.jsx("p",{className:"text-xs text-error mt-1",children:ue})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,tt)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},tt))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var mr,mi,Qt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,O]=w.useState(null),[I,A]=w.useState(null),[q,R]=w.useState(null),[re,ue]=w.useState(!1),[ye,B]=w.useState([]),[se,$]=w.useState(!1),[G,V]=w.useState(""),[H,T]=w.useState({markdownReady:!1,published:!1}),[z,F]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,he]=w.useState(null),[ge,De]=w.useState(!1),[ze,Fe]=w.useState(new Set),[we,He]=w.useState(new Map),[tt,st]=w.useState(!1),[it,Nt]=w.useState(null),[Be,ct]=w.useState(!1),[Te,qt]=w.useState(null),yi=w.useRef(new Map),Ct=w.useRef(null),Je=t.replace(/\.md$/,"");w.useEffect(()=>{var te;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),qt(c.cutId)),(te=S.current)==null||te.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ve;if(Te==null)return;const te=yi.current.get(Te);te&&((ve=te.scrollIntoView)==null||ve.call(te,{behavior:"smooth",block:"center"}),qt(null))},[Te,x]);const ee=w.useCallback(async()=>{var te;try{const ve=await i(`/api/stories/${e}/cuts/${Je}`);if(ve.status===404){b(null);return}if(!ve.ok){const me=await ve.json();O(me.error||"Failed to load cuts");return}const Y=await ve.json();b(Y),O(null);try{const me=await i(`/api/stories/${e}/${t}`);if(me.ok){const _e=await me.json(),Oe=typeof(_e==null?void 0:_e.content)=="string"?_e.content:"",Pe=Array.isArray(Y==null?void 0:Y.cuts)?Y.cuts:[],qe=Oe.length>0&&KS(Oe,Pe).ready,wt=(_e==null?void 0:_e.status)==="published"||(_e==null?void 0:_e.status)==="published-not-indexed";T({markdownReady:qe,published:wt})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(te=v.current)==null||te.call(v)}catch{O("Failed to load cuts")}finally{M(!1)}},[i,e,Je,t]),be=w.useCallback(async te=>!!(await i(`/api/stories/${e}/cuts/${Je}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)})).ok,[i,e,Je]),Me=w.useCallback(async()=>{st(!1);try{const te=await i(`/api/stories/${e}/cuts/${Je}/detect-clean-images`);if(!te.ok)return;const ve=await te.json();Fe(new Set(Array.isArray(ve.detected)?ve.detected:[]));const Y=new Map,me=ve.stale;if(Array.isArray(me))for(const _e of me){if(typeof(_e==null?void 0:_e.cutId)!="number"||typeof(_e==null?void 0:_e.message)!="string")continue;const Oe=Y.get(_e.cutId)??[];Oe.push(_e.message),Y.set(_e.cutId,Oe)}He(Y),st(!0)}catch{}},[i,e,Je]),$e=w.useCallback(async()=>{Nt(null);try{const te=await i(`/api/stories/${e}/cuts/${Je}/asset-diagnostics`);if(!te.ok)return;const ve=await te.json();Nt(Array.isArray(ve.diagnostics)?ve.diagnostics:null)}catch{}},[i,e,Je]),Xe=w.useCallback(async()=>{ct(!0);try{await Promise.all([ee(),Me(),$e()])}finally{ct(!1)}},[ee,Me,$e]),Wt=w.useCallback(async(te,ve={})=>{var _e;if(!x)return!1;const Y=x.cuts.find(Oe=>Oe.id===te);if(!Y||!Mo(Y)||(((_e=Y.overlays)==null?void 0:_e.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const me=hy(Y);if(me.length===0)return oe(`Cut ${Y.id}: no script lines available to draft.`),!1;he(te),oe(null);try{const Oe={...x,cuts:x.cuts.map(qe=>qe.id===te?{...qe,overlays:me,aiDraft:_y(me)}:qe)};return await be(Oe)?(oe(`Cut ${Y.id}: AI draft ready`),await ee(),ve.openEditor&&R(te),!0):(oe(`Cut ${Y.id}: AI draft failed`),!1)}finally{he(null)}},[x,be,ee]),pi=w.useCallback(async()=>{if(!x)return;const te=x.cuts.filter(ve=>{var Y;return Mo(ve)&&(((Y=ve.overlays)==null?void 0:Y.length)??0)===0&&!ve.finalImagePath&&!ve.uploadedCid&&!ve.uploadedUrl});if(te.length===0){oe("No unlettered cuts need an AI draft");return}De(!0),oe(null);try{const ve={...x,cuts:x.cuts.map(me=>{if(!te.some(Oe=>Oe.id===me.id))return me;const _e=hy(me);return _e.length>0?{...me,overlays:_e,aiDraft:_y(_e)}:me})};if(!await be(ve)){oe("AI draft failed");return}oe(`AI draft ready for ${te.length} cut${te.length===1?"":"s"}`),await ee()}finally{De(!1)}},[x,be,ee]),Rt=w.useCallback(async()=>{F(!0),oe(null),B([]);try{const te=await i(`/api/stories/${e}/cuts/${Je}/sync-clean-images`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Sync failed");else{const Y=Array.isArray(ve.synced)?ve.synced.length:0,me=Array.isArray(ve.cleared)?ve.cleared.length:0,_e=Array.isArray(ve.rejected)?ve.rejected:[];_e.length>0&&B(_e.map(Pe=>`Cut ${Pe.cutId}: ${Pe.reason}`));const Oe=[];Y>0&&Oe.push(`Synced ${Y}`),me>0&&Oe.push(`Cleared ${me} stale path${me===1?"":"s"}`),oe(Oe.length>0?Oe.join(", "):"No new clean images"),await ee(),await Me(),await $e()}}catch{oe("Sync failed")}F(!1)},[i,e,Je,ee,Me,$e]),St=w.useCallback(async(te,ve)=>{try{const Y=await i(HS(e,ve));if(!Y.ok)return!1;const me=await Y.blob(),_e=await Ku(new File([me],"clean.png",{type:me.type||"image/png"})),Oe=_e.type==="image/jpeg"?"jpg":"webp",Pe=new FormData;return Pe.append("file",new File([_e],`clean.${Oe}`,{type:_e.type})),(await i(`/api/stories/${e}/cuts/${Je}/upload-clean/${te}`,{method:"POST",body:Pe})).ok}catch{return!1}},[i,e,Je]),Gt=w.useCallback(async te=>{X(!0),Z(null);let ve=0;const Y=[];for(const me of te)await St(me.cutId,me.pngPath)?ve++:Y.push(me.cutId);await Xe(),X(!1),Z(Y.length===0?`Converted ${ve} image${ve===1?"":"s"} to WebP`:`Converted ${ve}; ${Y.length} failed (Cut ${Y.join(", ")}) — try Convert image on each`)},[St,Xe]),ot=w.useCallback(async()=>{var _e;if(!x)return;$(!0),V(""),B([]);const te=x.cuts.filter(Oe=>Oe.finalImagePath&&!Oe.uploadedCid),ve=[],Y=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Oe})=>V(`Upload limit reached — waiting ${Math.round(Oe/1e3)}s before continuing…`)});for(let Oe=0;Oe{const Kt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Kt.ok){const{cid:Gn,url:Dn}=await Kt.json();return{ok:!0,status:Kt.status,cid:Gn,url:Dn}}const Jt=await Kt.json().catch(()=>({}));return{ok:!1,status:Kt.status,errorMessage:Jt.error}},{...a,onWaiting:({attempt:Kt,maxRetries:Jt,waitMs:Gn})=>V(`Cut ${Pe.id} rate-limited — waiting ${Math.round(Gn/1e3)}s before retry ${Kt}/${Jt}...`)});if(!Ze.ok){ve.push(`Cut ${Pe.id}: upload failed — ${Ze.errorMessage||"unknown"}`);continue}const{cid:Qe,url:Vt}=Ze;(await i(`/api/stories/${e}/cuts/${Je}/set-uploaded/${Pe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Qe,url:Vt})})).ok||ve.push(`Cut ${Pe.id}: failed to record upload`)}catch(qe){ve.push(`Cut ${Pe.id}: ${qe instanceof Error?qe.message:"failed"}`)}}if(ve.length>0){B(ve),$(!1),V(""),ee();return}V("Preparing episode for publishing…");const me=await i(`/api/stories/${e}/cuts/${Je}/generate-markdown`,{method:"POST"});if(me.ok){const Oe=await me.json();((_e=Oe.warnings)==null?void 0:_e.length)>0&&B(Oe.warnings)}$(!1),V(""),ee()},[x,i,e,Je,a,ee]),Ht=w.useCallback(async()=>{j(!0),oe(null);try{const te=await i(`/api/stories/${e}/cuts/${Je}/repair-asset-paths`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Repair failed");else{const Y=Array.isArray(ve.cleared)?ve.cleared.length:0;oe(Y>0?`Cleared ${Y} stale path${Y===1?"":"s"}`:"No stale paths to clear"),await ee(),await Me()}}catch{oe("Repair failed")}j(!1)},[i,e,Je,ee,Me]),[U,Ce]=w.useState(!1),Ae=w.useCallback(async(te,ve=!0)=>{if(x){Ce(!0);try{const Y=x.cuts.reduce((qe,wt)=>Math.max(qe,wt.id),0)+1,me={id:Y,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"},_e=[...x.cuts];_e.splice(Math.max(0,Math.min(te,_e.length)),0,me);const Oe={...x,cuts:_e},Pe=await i(`/api/stories/${e}/cuts/${Je}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Oe)});if(Pe.ok)ve?R(Y):A(Y),await ee();else{const qe=await Pe.json().catch(()=>({}));oe(qe.error||"Could not add text panel")}}catch{oe("Could not add text panel")}Ce(!1)}},[x,i,e,Je,ee]),Ne=w.useCallback(()=>Ae((x==null?void 0:x.cuts.length)??0,!0),[Ae,x]);if(w.useEffect(()=>{ee(),Me(),$e()},[ee,Me,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Je,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:ee,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(te=>te.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:Je,language:s,authFetch:i,targetLabel:gn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(te,ve)=>{const Y={...x,cuts:x.cuts.map(_e=>_e.id===q?{..._e,overlays:te,aiDraft:ve??_e.aiDraft??null}:_e)};if(!await be(Y))throw new Error("Failed to save overlays")},onExported:()=>ee(),onClose:()=>{R(null),ee()}});const Ue=x.cuts.reduce((te,ve)=>{const Y=r1(ve);return te[Y]++,te},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(te=>!gn(te)).length,_t=x.cuts.filter(te=>GS(te)).map(te=>te.id),At=uD({cuts:x.cuts,published:H.published}),Bt=((mr=At.steps.find(te=>te.key==="upload"))==null?void 0:mr.status)==="done",Ut=x.cuts.some(te=>te.finalImagePath&&!te.uploadedCid)||Bt&&!H.markdownReady,Yt=(it??[]).filter(te=>te.state==="needs-conversion"&&te.convertiblePng).map(te=>({cutId:te.cutId,pngPath:te.convertiblePng})),an=new Map(Yt.map(te=>[te.cutId,te.pngPath])),ai=(it??[]).filter(te=>te.state==="needs-conversion"&&te.issue).map(te=>te.issue),An=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mi=Je.match(/\d+/))==null?void 0:mi[0])??"0",10)+1}`,Rn=typeof x.title=="string"?x.title:null,lr=x.cuts.filter(te=>!gn(te)),Pi={cuts:x.cuts.length,artwork:lr.filter(te=>te.cleanImagePath||an.has(te.id)).length,converted:lr.filter(te=>te.cleanImagePath&&/\.(webp|jpe?g)$/i.test(te.cleanImagePath)).length,lettered:x.cuts.filter(te=>{var ve;return(((ve=te.overlays)==null?void 0:ve.length)??0)>0||!!te.finalImagePath}).length,uploaded:x.cuts.filter(te=>te.uploadedCid||te.uploadedUrl).length},vn=x.cuts.filter(te=>{var ve;return Mo(te)&&(((ve=te.overlays)==null?void 0:ve.length)??0)===0&&!te.finalImagePath&&!te.uploadedCid&&!te.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:An}),Rn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Rn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Pi.cuts," cuts · ",Pi.artwork," artwork found ·"," ",Pi.converted," converted · ",Pi.lettered," ","lettered · ",Pi.uploaded," uploaded"]})]}),vn>0&&d.jsx("button",{onClick:pi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${vn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{ue(!0),B([]);try{const te=await i(`/api/stories/${e}/cuts/${Je}/generate-markdown`,{method:"POST"});if(te.ok){const ve=await te.json();B(ve.warnings||[])}}catch{}ue(!1)},disabled:re,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:re?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ne,disabled:U,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:U?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Xe,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"}),d.jsx("button",{onClick:Rt,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"}),d.jsx("button",{onClick:ot,disabled:se||!(x!=null&&x.cuts.some(te=>te.finalImagePath&&!te.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),_t.length>0&&d.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:[_t.length===1?"Cut":"Cuts"," ",_t.join(", ")," ",_t.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",_t.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),tt&&dt>0&&Ue.missing===0&&we.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Yt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Yt.length," PNG image",Yt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Gt(Yt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ai.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ai.map((te,ve)=>d.jsx("li",{children:te},ve))})]})]}),it&&it.length>0&&(()=>{const te=tM(it),ve=it.filter(Y=>Y.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",te.uploaded," uploaded · ",te.finalReady," final ·"," ",te.cleanReady," clean · ",te.planned," planned",te.needsConversion>0?` · ${te.needsConversion} needs conversion`:"",te.missing>0?` · ${te.missing} missing`:""]}),ve.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ve.map(Y=>d.jsx("li",{children:Y.issue},Y.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:ye,onFinish:ot,finishing:se,progressText:G,canFinish:Ut,markdownReady:H.markdownReady,published:H.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((te,ve)=>{var Y;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ve,beforeLabel:ve===0?"Episode opening":`After cut ${(Y=x.cuts[ve-1])==null?void 0:Y.id}`,afterLabel:`Before cut ${te.id}`,disabled:U,onAdd:()=>Ae(ve)}),d.jsx(sM,{cut:te,storyName:e,plotFile:Je,language:s,expanded:I===te.id,onToggle:()=>A(I===te.id?null:te.id),authFetch:i,onUpdated:()=>{ee(),Me(),$e()},onOpenEditor:()=>R(te.id),detectedLocalClean:ze.has(te.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Wt(te.id,{openEditor:!0})},aiDrafting:K===te.id,staleMessages:we.get(te.id)??[],onRepairStale:Ht,repairing:xe,conversionPng:an.get(te.id)??null,onConvert:St,converting:D,rowRef:me=>{me?yi.current.set(te.id,me):yi.current.delete(te.id)}})]},te.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Qt=x.cuts[x.cuts.length-1])==null?void 0:Qt.id}`,afterLabel:"Episode ending",disabled:U,onAdd:()=>Ae(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Ho(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 dM(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 Ip(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 Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...dl,attributes:{...dl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:O=null,onWorkflowActionHandled:I}){const[A,q]=w.useState(null),[R,re]=w.useState(!1),[ue,ye]=w.useState("preview"),[B,se]=w.useState("publish"),[$,G]=w.useState("text"),[V,H]=w.useState(null),T=w.useCallback((ne,Ee)=>{ye("edit"),H(je=>({cutId:ne,openEditor:Ee,seq:((je==null?void 0:je.seq)??0)+1}))},[]),[z,F]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,he]=w.useState(""),[ge,De]=w.useState(""),[ze,Fe]=w.useState(!1),[we,He]=w.useState(null),[tt,st]=w.useState(0),[it,Nt]=w.useState(0),[Be,ct]=w.useState(null),[Te,qt]=w.useState(null),[yi,Ct]=w.useState(null),[Je,ee]=w.useState(0),be=w.useRef(null),Me=w.useRef(!1),[$e,Xe]=w.useState(!1),[Wt,pi]=w.useState(ol[0]),[Rt,St]=w.useState(rs[0]),[Gt,ot]=w.useState(!1),[Ht,U]=w.useState(null),[Ce,Ae]=w.useState(null),[Ne,Ge]=w.useState(!1),[Ue,dt]=w.useState(!1),[_t,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Yt,an]=w.useState(!1),ai=w.useRef(null),An=w.useRef(null),[Rn,lr]=w.useState(!1),[Pi,vn]=w.useState(null),[mr,mi]=w.useState(null),[Qt,te]=w.useState("unknown"),ve=w.useRef(!1),[Y,me]=w.useState(!1),[_e,Oe]=w.useState(!1),[Pe,qe]=w.useState(null),[wt,vt]=w.useState([]),[jt,Ze]=w.useState(null),Qe=w.useRef(null),Vt=w.useRef(null),Ri=w.useRef(0),Kt=w.useCallback(async()=>{if(!e||!t){q(null);return}const ne=`${e}/${t}`,Ee=Vt.current!==ne;Ee&&(Vt.current=ne);try{const je=await i(`/api/stories/${e}/${t}`);if(je.ok){const nt=await je.json();q(nt),(Ee||!Me.current)&&(F(nt.content??""),Ee&&(X(!1),Me.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{re(!0),Kt().finally(()=>re(!1))},[Kt]),w.useEffect(()=>{if(!e||!t||ue==="edit"&&D)return;const ne=setInterval(Kt,3e3);return()=>clearInterval(ne)},[e,t,Kt,ue,D]);const[Jt,Gn]=w.useState(null),Dn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Dn||!e){Gn(null);return}let ne=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{ne||Gn(Ee?Op(Ee.cuts||[]):null)}).catch(()=>{ne||Gn(null)}),()=>{ne=!0}},[Dn,e,i]);const Br=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!Br||!e||!t){He(null),st(0),Nt(0),ct(null);return}let ne=!1;const Ee=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[je,nt]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Ee}`)]);if(ne)return;if(!nt.ok){He("error"),st(0),Nt(0),ct(null);return}const Lt=await nt.json(),gi=Lt.cuts||[],vr=je.ok?(await je.json()).content??"":"",xi=XS(vr,gi);ne||(He(xi.stage),st(xi.awaitingCount),Nt(xi.totalCuts),ct(Op(gi)),Ct(typeof Lt.title=="string"?Lt.title:null))}catch{ne||(He("error"),st(0),Nt(0),ct(null))}})(),()=>{ne=!0}},[Br,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,Je]),w.useEffect(()=>{if(!e){qt(null);return}let ne=!1;return i(`/api/stories/${e}/structure.md`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{ne||qt((Ee==null?void 0:Ee.content)??null)}).catch(()=>{}),()=>{ne=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ne=Cu(p);let Ee=ne??"";if(!ne&&Te){const nt=Te.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);nt&&(Ee=Cu(nt[1].replace(/\*+/g,"").trim())??"")}he(Ee);let je=h&&rs.find(nt=>nt.toLowerCase()===h.toLowerCase())||"";if(!je&&Te){const nt=Te.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);nt&&(je=rs.find(Lt=>Lt.toLowerCase()===nt[1].replace(/\*+/g,"").trim().toLowerCase())||"")}De(je),Fe(f??!1)},[e,p,h,f,Te]);const cs=w.useCallback(ne=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Me.current=!1,q(Ee=>Ee&&{...Ee,content:z}))}catch{}j(!1)}},[e,t,i,z]),Xt=w.useCallback(async()=>{if(!e||!t)return;const ne=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ne}/generate-markdown`,{method:"POST"})).ok&&(await Kt(),ee(je=>je+1))}catch{}},[e,t,i,Kt]);w.useEffect(()=>{if(O&&O.seq!==Ri.current){switch(Ri.current=O.seq,O.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ye("edit"),G("cuts");break;case"generate-markdown":Xt();break;case"publish":ye("preview");break}I==null||I(O.seq)}},[O,x,Xt,I]);const Ii=w.useCallback(ne=>{var nt;const Ee=(nt=ne.target.files)==null?void 0:nt[0];if(!Ee)return;ve.current=!0,vn(null),mi(null);const je=Sy(Ee);if(je){U(null),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ai.current&&(ai.current.value=""),Ut(je),te("invalid");return}U(Ee),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(Ee))),Ut(null),te("selected")},[]),Di=w.useCallback(async ne=>{var je;const Ee=(je=ne.target.files)==null?void 0:je[0];if(An.current&&(An.current.value=""),!(!Ee||!e)){ve.current=!0,vn(null),lr(!0),Ut(null);try{let nt;try{nt=await Ku(Ee)}catch(dn){U(null),Ae(Ys=>(Ys&&URL.revokeObjectURL(Ys),null)),Ut(dn instanceof Error?dn.message:"Could not import image");return}const Lt=nt.type==="image/jpeg"?"jpg":"webp",gi=new File([nt],`cover.${Lt}`,{type:nt.type}),vr=new FormData;vr.append("file",gi);const xi=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:vr});if(!xi.ok){const dn=await xi.json().catch(()=>({}));Ut(dn.error||"Cover import failed");return}U(gi),Ae(dn=>(dn&&URL.revokeObjectURL(dn),URL.createObjectURL(gi))),mi(null),te("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{lr(!1)}}},[e,i]),or=w.useCallback(async ne=>{if(ne.size>1024*1024){qe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ne.type)){qe("Only WebP and JPEG images are accepted");return}Oe(!0),qe(null);try{const je=new FormData;je.append("file",ne);const nt=await i("/api/publish/upload-plot-image",{method:"POST",body:je});if(!nt.ok){const gi=await nt.json();throw new Error(gi.error||"Upload failed")}const Lt=await nt.json();vt(gi=>[...gi,{cid:Lt.cid,url:Lt.url}])}catch(je){qe(je instanceof Error?je.message:"Upload failed")}finally{Oe(!1),Qe.current&&(Qe.current.value="")}},[i]),Gs=w.useCallback(ne=>{var je;const Ee=(je=ne.target.files)==null?void 0:je[0];Ee&&or(Ee)},[or]),ei=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ge(!0),Ut(null),an(!1);try{let ne;if(Ht){const je=new FormData;je.append("file",Ht);const nt=await i("/api/publish/upload-cover",{method:"POST",body:je});if(!nt.ok){const gi=await nt.json();throw new Error(gi.error||"Cover upload failed")}ne=(await nt.json()).cid}const Ee=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...ne!==void 0&&{coverCid:ne},genre:Wt,language:Rt,isNsfw:Gt})});if(!Ee.ok){const je=await Ee.json();throw new Error(je.error||"Update failed")}an(!0),U(null),ne!==void 0&&(At(!0),Ae(je=>(je&&URL.revokeObjectURL(je),null)),te("unknown"),ai.current&&(ai.current.value="")),setTimeout(()=>an(!1),3e3)}catch(ne){Ut(ne instanceof Error?ne.message:"Update failed")}finally{Ge(!1)}}},[A==null?void 0:A.storylineId,Ht,Wt,Rt,Gt,i]);w.useEffect(()=>{Xe(!1),U(null),Ae(null),Ut(null),an(!1),dt(!1),me(!1),vt([]),qe(null),vn(null),mi(null),te("unknown"),ve.current=!1,G("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||ve.current)return;let ne=!1;return(async()=>{try{const Ee=await i(`/api/stories/${e}/cover-asset`);if(ne||!Ee.ok)return;const je=await Ee.json();if(ne)return;if(!(je!=null&&je.found)){te("none");return}if(!je.valid){mi(je.error||"Detected cover asset is invalid and was not used"),te("invalid");return}const nt=await i(`/api/stories/${e}/asset/${je.path.replace(/^assets\//,"")}`);if(ne||!nt.ok)return;const Lt=await nt.blob(),gi=new File([Lt],je.path.split("/").pop()||"cover.webp",{type:je.type});if(Sy(gi)||ne||ve.current)return;U(gi),Ae(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(gi))),vn(je.path),te("detected")}catch{}})(),()=>{ne=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;dt(!1);const ne="https://plotlink.xyz";let Ee=!1;return fetch(`${ne}/api/storyline/${A.storylineId}`).then(je=>je.ok?je.json():null).then(je=>{if(!Ee){if(!je){Ut("Could not load current story metadata");return}if(je.genre){const nt=Cu(je.genre);nt&&pi(nt)}if(je.language){const nt=rs.find(Lt=>Lt.toLowerCase()===je.language.toLowerCase());nt&&St(nt)}je.isNsfw!==void 0&&ot(!!je.isNsfw),At(!!(je.coverCid||je.coverUrl||je.cover)),dt(!0)}}).catch(()=>{Ee||Ut("Could not load current story metadata")}),()=>{Ee=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(ue!=="edit")return;const ne=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key==="s"&&(Ee.preventDefault(),gr())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[ue,gr]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const ne=new Date(A.publishedAt).getTime(),Ee=300*1e3,je=()=>{const Lt=Math.max(0,Ee-(Date.now()-ne));oe(Lt)};je();const nt=setInterval(je,1e3);return()=>clearInterval(nt)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const Mn=ae!==null&&ae<=0,Lr=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Si=(ue==="edit"?z:(A==null?void 0:A.content)??"").length,wi=t==="genesis.md",Bn=t?/^plot-\d+\.md$/.test(t):!1,Xi=c==="cartoon"&&Bn,Zi=c==="cartoon"&&wi,us=Zi||Xi,Or=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",zr=S&&us,Ko=Zi?Jt?Jt.total:null:Xi?we===null?null:it:null,Sa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Or,cutCount:Ko,cutProgress:Zi?Jt:null}),_l=(Zi||Xi)&&!Or,Pr=_l?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:Te,contentType:"cartoon",episodeTitle:yi}):null,bl=!!Pr&&Ho(Pr,t),Xo=Xi&&!Or&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:yi}),xr=Zi&&!Or?wm((A==null?void 0:A.content)??""):null,Yn=!!xr&&xr.blockers.length>0,vl="w-full max-w-[32rem] rounded-xl border px-3 py-3",yl={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ir=ne=>{if(!Zi)return null;const Ee=cM({hasSelectedCover:!!Ht,invalid:Qt==="invalid",attached:ne});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Ee.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${yl[Ee.tone]}`,children:Ee.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},_r=bl||Xo,Zo=()=>{if(!_l||!Pr)return null;const ne=wi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":bl?"true":"false","data-blocked":_r?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ne,":"]})," ",d.jsx("span",{className:_r?"text-error font-medium":"text-foreground",children:Pr})]}),bl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",wi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Xo?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Pr,"” 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]})},Sl=()=>xr?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Yn?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),xr.blockers.map((ne,Ee)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ne},`b-${Ee}`)),xr.warnings.map((ne,Ee)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ne},`w-${Ee}`))]}):null,hs=wi||Bn?1e4:null,br=!Or&&hs!==null&&Si>hs,cr=(A==null?void 0:A.content)??"",ds=Or?{count:0,warnings:[]}:yM(cr),fs=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:be,value:z,onChange:ne=>{F(ne.target.value),X(!0),Me.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!zr&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${br?"text-error font-medium":"text-muted"}`,children:[Si.toLocaleString(),hs!==null?`/${hs.toLocaleString()}`:" chars"]}),br&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Si-hs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ye("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ye("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),ue==="preview"?Xi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:we}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Xi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(ne=>ne+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Zi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>G("text"),className:`px-2 py-0.5 text-[11px] rounded ${$==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>G("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${$==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:$==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(ne=>ne+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):fs})]}):fs,!zr&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:Sa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Mn&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),Kt())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),Bn&&d.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,K,ge,Pe)},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"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:Gs?gr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gr?"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."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var Ne;const ne=`https://plotlink.xyz/story/${A.storylineId}`;if(!gr)return ne;const ke=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ne}/${ke}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),mi&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Ke(ne=>!ne),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&mi&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Pr(vt),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{$(null),Ee(null),pi(null),Q("unknown"),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:Yi,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Yt,onChange:ne=>fi(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:cl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))}),d.jsx("select",{value:Rt,onChange:ne=>St(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ns.map(ne=>d.jsx("option",{value:ne,children:ne},ne))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Ht,onChange:ne=>nt(ne.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Mn,disabled:Ae||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ae?"Saving...":Ue?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Vi&&Oe&&Oe.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Oe.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.withClean,"/",Oe.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.withText,"/",Oe.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Oe.uploaded,"/",Oe.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Ki&&ti&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ti.total," planned",ti.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ti.withClean," clean ·"," ",ti.withText," lettered ·"," ",ti.exported," exported ·"," ",ti.uploaded," uploaded"]})]}),(Ki||Vi)&&wa&&d.jsxs("div",{className:`${vl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Ko===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Ki?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:wa})]}),gr&&!Vi&&he==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ce,onChange:ne=>ye(ne.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),ce&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 ne;return(ne=Ze.current)==null?void 0:ne.click()},onDragOver:ne=>{ne.preventDefault(),ne.stopPropagation()},onDrop:ne=>{var Ne;ne.preventDefault(),ne.stopPropagation();const ke=(Ne=ne.dataTransfer.files)==null?void 0:Ne[0];ke&&pr(ke)},children:[d.jsx("input",{ref:Ze,type:"file",accept:"image/webp,image/jpeg",onChange:si,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Te?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Le&&d.jsx("span",{className:"text-error text-xs",children:Le}),ft.map((ne,ke)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ne.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ne.url})`),Ct(ke),setTimeout(()=>Ct(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:rt===ke?"Copied!":"Copy"})]})]},ne.cid))]})]}),mi&&c!=="cartoon"&&!(he==="edit"&&F==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Pr(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{P.current=!0,Sn(null),pi(null),Q("unknown"),$(null),Ee(ne=>(ne&&URL.revokeObjectURL(ne),null)),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:Yi,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:vn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Ai,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ne;return(ne=vn.current)==null?void 0:ne.click()},disabled:Wn,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:Wn?"Importing…":"Import generated image (PNG ok)"}),Xt&&d.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."}),yn&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",yn," — pick a file to override."]}),fr&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[fr," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Zt==="none"&&!Xt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!cs&&Zo(),!cs&&Sl(),!cs&&d.jsxs("div",{className:"flex items-center gap-2",children:[mi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:ne=>{de(ne.target.value),ne.target.value&&Ws({genre:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),cl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:ne=>{Me(ne.target.value),ne.target.value&&Ws({language:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ns.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(hs.count>0){const ke=`This plot contains ${hs.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,K,ge,ze)},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"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:Mn?Bn?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":Bn?"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."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var je;const ne=`https://plotlink.xyz/story/${A.storylineId}`;if(!Bn)return ne;const Ee=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((je=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:je[1])??"1");return`${ne}/${Ee}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),wi&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Xe(ne=>!ne),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&wi&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ir(_t),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{U(null),Ae(null),mi(null),te("unknown"),ai.current&&(ai.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ai,type:"file",accept:"image/webp,image/jpeg",onChange:Ii,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Wt,onChange:ne=>pi(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ol.map(ne=>d.jsx("option",{value:ne,children:ne},ne))}),d.jsx("select",{value:Rt,onChange:ne=>St(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:rs.map(ne=>d.jsx("option",{value:ne,children:ne},ne))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Gt,onChange:ne=>ot(ne.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:ei,disabled:Ne||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ne?"Saving...":Ue?"Save Changes":"Loading..."}),Yt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Xi&&Be&&Be.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Be.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withClean,"/",Be.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withText,"/",Be.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.uploaded,"/",Be.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Zi&&Jt&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Jt.total," planned",Jt.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Jt.withClean," clean ·"," ",Jt.withText," lettered ·"," ",Jt.exported," exported ·"," ",Jt.uploaded," uploaded"]})]}),(Zi||Xi)&&Sa&&d.jsxs("div",{className:`${vl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Ko===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Zi?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:Sa})]}),Bn&&!Xi&&ue==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Y,onChange:ne=>me(ne.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Y&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 ne;return(ne=Qe.current)==null?void 0:ne.click()},onDragOver:ne=>{ne.preventDefault(),ne.stopPropagation()},onDrop:ne=>{var je;ne.preventDefault(),ne.stopPropagation();const Ee=(je=ne.dataTransfer.files)==null?void 0:je[0];Ee&&or(Ee)},children:[d.jsx("input",{ref:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:Gs,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:_e?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Pe&&d.jsx("span",{className:"text-error text-xs",children:Pe}),wt.map((ne,Ee)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ne.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ne.url})`),Ze(Ee),setTimeout(()=>Ze(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:jt===Ee?"Copied!":"Copy"})]})]},ne.cid))]})]}),wi&&c!=="cartoon"&&!(ue==="edit"&&$==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ir(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(ne=>(ne&&URL.revokeObjectURL(ne),null)),ai.current&&(ai.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ai,type:"file",accept:"image/webp,image/jpeg",onChange:Ii,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:An,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Di,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ne;return(ne=An.current)==null?void 0:ne.click()},disabled:Rn,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:Rn?"Importing…":"Import generated image (PNG ok)"}),Ht&&d.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."}),Pi&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Pi," — pick a file to override."]}),mr&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[mr," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Qt==="none"&&!Ht&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!us&&Zo(),!us&&Sl(),!us&&d.jsxs("div",{className:"flex items-center gap-2",children:[wi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:ne=>{he(ne.target.value),ne.target.value&&cs({genre:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),ol.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:ne=>{De(ne.target.value),ne.target.value&&cs({language:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),rs.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ds.count>0){const Ee=`This plot contains ${ds.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(ke))return}const ne=mi?Xt:null;ne?await(s==null?void 0:s(e,t,K,ge,Pe,ne))&&(P.current=!0,Sn(null),pi(null),Q("unknown"),$(null),Ee(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),ri.current&&(ri.current.value="")):s==null||s(e,t,K,ge,Pe)},disabled:!!a||br||_r||Gn||mi&&(!K||!ge)||Vi&&Se!=="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"}),mi&&c==="cartoon"&&(!K||!ge)&&d.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"}),mi&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),mi&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),br&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Vi&&Se==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Vi&&Se==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Vi&&Se==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",Je," of ",et," ","still need an uploaded image"]})]}),cs&&d.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 →"}),hs.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:hs.warnings.map((ne,ke)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ne},ke))}),mi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Pe,onChange:ne=>{Fe(ne.target.checked),Ws({isNsfw:ne.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),Pe&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,O]=w.useState("cartoon"),[H,A]=w.useState("unknown"),[W,R]=w.useState(!1),[re,he]=w.useState(!1),[be,B]=w.useState(null),[se,F]=w.useState(!1),[Y,V]=w.useState(null),[U,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),he(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&ns.find(de=>de.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),O(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const q=w.useCallback(async()=>{R(!0),he(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)he(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){F(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(Pe){B(Pe instanceof Error?Pe.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",de=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",de);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!Me.ok){const Pe=await Me.json().catch(()=>({}));B(Pe.error||"Cover import failed.");return}A("present"),V(Pe=>(Pe&&URL.revokeObjectURL(Pe),URL.createObjectURL(de)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;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.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=H==="present"?"Cover set":H==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=H==="present"?"text-green-700":H==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.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:[d.jsx("option",{value:"",children:"Needs metadata"}),cl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(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:[d.jsx("option",{value:"",children:"Needs metadata"}),ns.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[Y&&d.jsx("img",{src:Y,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("button",{type:"button",onClick:j,"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:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),he(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:q,disabled:W,"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:W?"Saving…":"Save Story Info"}),re&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var et,jt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[O,H]=w.useState(null),[A,W]=w.useState(null),[R,re]=w.useState(null),[he,be]=w.useState(null),B=async()=>{try{const Oe=await t(`/api/stories/${e}/cover-asset`),ct=Oe.ok?await Oe.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const je=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!je.ok)return null;const Gt=await je.blob();return new File([Gt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||Gt.type})}catch{return null}};w.useEffect(()=>{let Oe=!1;return(async()=>{v(!0),N(!1);try{const je=await t(`/api/stories/${e}/progress`),Gt=je.ok?await je.json():null;if(Oe)return;!Gt||!Array.isArray(Gt.episodes)?(N(!0),x(null)):x(Gt),v(!1)}catch{Oe||(N(!0),x(null),v(!1))}})(),()=>{Oe=!0}},[e,t,f]);const se=((jt=(et=_==null?void 0:_.episodes)==null?void 0:et.find(Oe=>!Oe.published))==null?void 0:jt.file)??null,F=se==="genesis.md",Y=JSON.stringify([se??"",f]),[V,U]=w.useState(null);if(V!==Y&&(U(Y),H(null),W(null),re(null),be(null)),w.useEffect(()=>{if(!se)return;let Oe=!1;const ct=se.replace(/\.md$/,"");return(async()=>{var je;try{const Gt=[t(`/api/stories/${e}/${se}`),t(`/api/stories/${e}/cuts/${ct}`)];F&&Gt.push(t(`/api/stories/${e}/structure.md`));const[yi,kt,Xe]=await Promise.all(Gt);if(Oe)return;if(H(yi.ok?(await yi.json()).content??"":""),kt.ok){const te=await kt.json();if(Oe)return;W(Array.isArray(te.cuts)?te.cuts:[]),re(typeof te.title=="string"?te.title:null)}else W(null),re(null);be(F&&Xe&&Xe.ok?((je=await Xe.json())==null?void 0:je.content)??null:null)}catch{Oe||(H(""),W(null),re(null),be(null))}})(),()=>{Oe=!0}},[se,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Oe=>!Oe.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=T.cuts,q=_.cover==="present",xe=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:q?"done":"todo",detail:q?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=O!==null,oe=ae?Nm({fileName:T.file,fileContent:O??"",storySlug:e,structureContent:he,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Ho(oe,T.file),de=!X&&ae&&!Em({fileContent:O??"",episodeTitle:R}),ge=K||de,Me=X&&ae?wm(O??""):null,Pe=!!Me&&Me.blockers.length>0,Fe=!X&&ae&&A!==null?XS(O??"",A):null,Se=Fe&&Fe.stage==="error"?Fe.issues:[],Je=j&&C&&(ae&&(X||A!==null))&&!ge&&!Pe&&!Z&&!!a,at=async()=>{if(!(!Je||!a)){E(null);try{const Oe=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Oe)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Oe,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Oe.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Oe.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Oe.status==="done"?"✓":"○"}),d.jsx("span",{className:Oe.status==="done"?"text-foreground":"text-muted",children:Oe.label}),Oe.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Oe.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):de?d.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]}),Me&&d.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":Pe?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),Me.blockers.map((Oe,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Oe},`b-${ct}`)),Me.warnings.map((Oe,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Oe},`w-${ct}`))]}),Se.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(Se).map(Oe=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Oe.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Oe.title})},Oe.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:Se.map((Oe,ct)=>d.jsx("li",{className:"font-mono break-words",children:Oe},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!q&&d.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)"}),X&&!C&&d.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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.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 ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!Je,"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:Je?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||Pe?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Pe?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.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 qM(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 WM(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?Ho(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=qM(i,s);return a?Ho(a,t)||Ip(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,If=224,Hf=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[O,H]=w.useState(VM),[A,W]=w.useState([]),[R,re]=w.useState(!1),[he,be]=w.useState(""),[B,se]=w.useState(""),[F,Y]=w.useState(""),[V,U]=w.useState("English"),[T,z]=w.useState("normal"),[q,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[de,ge]=w.useState(new Set),[Me,Pe]=w.useState(new Set),[Fe,Se]=w.useState({}),[He,Je]=w.useState({}),[at,et]=w.useState({}),[jt,Oe]=w.useState({}),[ct,je]=w.useState({}),[Gt,yi]=w.useState({}),[kt,Xe]=w.useState(!1),[te,_e]=w.useState(!0),[Be,$e]=w.useState(null),Ke=w.useRef(new Map),Yt=w.useRef(new Map),fi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Ht=w.useRef(null),nt=w.useRef(null),Xt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(P=>P.ok?P.json():null).then(P=>{P!=null&&P.address&&E(P.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(P=>P.ok?P.json():null).then(P=>{P&&D(P)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(O))}catch{}},[O]),w.useEffect(()=>{const P=()=>{if(!nt.current)return;const ce=nt.current.getBoundingClientRect().width-If-Hf;H(ye=>jy(ye,ce))};return window.addEventListener("resize",P),P(),()=>window.removeEventListener("resize",P)},[]);const $=w.useCallback(()=>{be(""),se(""),Y(""),z("normal"),xe("claude"),re(!0)},[]),we=w.useCallback(async(P,ce,ye,Te)=>{const De=he.trim();if(!De)return;const Le=P==="cartoon"?"codex":Te;try{const tt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:ce,genre:F||void 0,contentType:P,agentMode:ye,agentProvider:Le})});if(!tt.ok)return;const ft=await tt.json();re(!1),Se(wt=>({...wt,[ft.name]:P})),Je(wt=>({...wt,[ft.name]:ce})),F&&et(wt=>({...wt,[ft.name]:F})),K(wt=>({...wt,[ft.name]:Le})),ye==="bypass"&&ae(wt=>({...wt,[ft.name]:!0})),s(ft.name),o(null)}catch{}},[t,he,B,F]);w.useEffect(()=>{if(A.length===0)return;const P=setInterval(async()=>{try{const ce=await t("/api/stories");if(!ce.ok)return;const ye=await ce.json(),Te=new Set(ye.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of Te)if(!St.current.has(De)&&A.length>0){const Le=A[0],tt=Ke.current.get(Le)||"fiction",ft=Yt.current.get(Le)||"English",wt=fi.current.get(Le)||"normal",rt=Rt.current.get(Le)||"claude";let Ct=!1;Ht.current&&(Ct=await Ht.current(Le,De,{contentType:tt,language:ft,agentMode:wt,agentProvider:rt}).catch(()=>!1)),Ct&&(W(Ze=>Ze.slice(1)),Ke.current.delete(Le),Yt.current.delete(Le),fi.current.delete(Le),Rt.current.delete(Le),wt==="bypass"&&ae(Ze=>{const Si={...Ze,[De]:!0};return delete Si[Le],Si}),K(Ze=>{const Si={...Ze,[De]:rt};return delete Si[Le],Si}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:tt,language:ft,agentMode:wt,agentProvider:rt})}).catch(()=>{})),s(De),o(null)}St.current=Te}catch{}},3e3);return()=>clearInterval(P)},[t,A]),w.useEffect(()=>{t("/api/stories").then(P=>{if(P.ok)return P.json()}).then(P=>{P!=null&&P.stories&&(St.current=new Set(P.stories.filter(ce=>ce.name!=="_example").map(ce=>ce.name)))}).catch(()=>{})},[t]);const Ee=w.useCallback((P,ce)=>{s(P),o(ce),h(null)},[]),Ae=w.useRef(null),Ye=w.useCallback(async P=>{var ce,ye,Te,De;Ae.current=P,s(P),o(null),h(null);try{const Le=await t(`/api/stories/${P}`);if(Le.ok&&Ae.current===P){const tt=await Le.json();if(tt.contentType==="cartoon")return;const ft=tt.files||[],rt=((ce=ft.map(Ct=>{var Ze;return{file:Ct.file,num:(Ze=Ct.file.match(/^plot-(\d+)\.md$/))==null?void 0:Ze[1]}}).filter(Ct=>Ct.num!=null).sort((Ct,Ze)=>parseInt(Ze.num)-parseInt(Ct.num))[0])==null?void 0:ce.file)??((ye=ft.find(Ct=>Ct.file==="genesis.md"))==null?void 0:ye.file)??((Te=ft.find(Ct=>Ct.file==="structure.md"))==null?void 0:Te.file)??((De=ft[0])==null?void 0:De.file);rt&&Ae.current===P&&o(rt)}}catch{}},[t]),Ue=w.useCallback(P=>{P.preventDefault(),Xt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const ce=Te=>{if(!Xt.current||!nt.current)return;const De=nt.current.getBoundingClientRect(),Le=De.width-If-Hf,tt=Te.clientX-De.left-If;H(jy(tt/Le,Le))},ye=()=>{Xt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",ce),window.removeEventListener("mouseup",ye)};window.addEventListener("mousemove",ce),window.addEventListener("mouseup",ye)},[]),ut=w.useCallback(async(P,ce,ye,Te,De,Le)=>{var rt;f(ce),v("Reading file..."),N(null);let tt=!1,ft=null,wt=!1;try{const Ct=await t(`/api/stories/${P}/${ce}`);if(!Ct.ok)throw new Error("Failed to read file");const Ze=await Ct.json(),Si=Fe[P];let Br=null,$t=null;if(ce==="genesis.md")try{const Ft=await t(`/api/stories/${P}/structure.md`);Ft.ok&&(Br=(await Ft.json()).content??null)}catch{}else if(Si==="cartoon"&&ce.match(/^plot-\d+\.md$/))try{const Ft=await t(`/api/stories/${P}/cuts/${ce.replace(/\.md$/,"")}`);Ft.ok&&($t=(await Ft.json()).title??null)}catch{}const ti=Nm({fileName:ce,fileContent:Ze.content,storySlug:P,structureContent:Br,contentType:Si,episodeTitle:$t});if(Si==="cartoon"&&Ho(ti,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(()=>{f(null),v("")},6e3),!1;if(Si==="cartoon"&&ce.match(/^plot-\d+\.md$/)&&!Em({fileContent:Ze.content,episodeTitle:$t}))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(()=>{f(null),v("")},6e3),!1;if(Si==="cartoon"&&ce==="genesis.md"){const Ft=wm(Ze.content).blockers;if(Ft.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Ft[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let hn;if(ce.match(/^plot-\d+\.md$/)){if(pM(Ze)){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(()=>{f(null),v("")},6e3);return}try{const Ft=await t(`/api/stories/${P}`);if(Ft.ok){const Yi=(await Ft.json()).files.find(Ai=>Ai.file==="genesis.md"&&Ai.storylineId);hn=Yi==null?void 0:Yi.storylineId}}catch{}if(!hn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Ft=await t("/api/publish/preflight");if(Ft.ok){const Dn=await Ft.json();if(gM(Dn))return N(xM(Dn)),f(null),v(""),!1}}catch{}v("Publishing...");const ar=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:P,fileName:ce,title:ti,content:Ze.content,genre:ye,language:Te,isNsfw:De,storylineId:hn,...wy(Fe,P,hn)?{contentType:wy(Fe,P,hn)}:{}})});if(!ar.ok){const Ft=await ar.json();throw new Error(Ft.error||"Publish failed")}const os=(rt=ar.body)==null?void 0:rt.getReader(),Ws=new TextDecoder;if(os)for(;;){const{done:Ft,value:Dn}=await os.read();if(Ft)break;const Ai=Ws.decode(Dn).split(` -`).filter(pr=>pr.startsWith("data: "));for(const pr of Ai)try{const si=JSON.parse(pr.slice(6));if(si.step&&v(si.message||si.step),si.step==="done"&&si.txHash){if(wt=!0,await t(`/api/stories/${P}/${ce}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:si.txHash,storylineId:si.storylineId,plotIndex:si.plotIndex,contentCid:si.contentCid,gasCost:si.gasCost,indexError:si.indexError,authorAddress:M})}),x(Mn=>Mn+1),Le&&ce==="genesis.md"&&si.storylineId){v("Uploading cover...");let Mn=null;try{Mn=await uM(t,si.storylineId,Le)}catch{}Mn||(tt=!0)}if(Si==="cartoon"&&si.storylineId)try{const Mn=ce!=="genesis.md",Gs=`storylineId=${si.storylineId}`+(Mn&&si.plotIndex!=null?`&plotIndex=${si.plotIndex}`:""),mr=await t(`/api/publish/public-title?${Gs}`);if(mr.ok){const Sa=await mr.json(),Oi=Mn?{plots:Sa.plotTitle!=null?[{plotIndex:si.plotIndex,title:Sa.plotTitle}]:[]}:{title:Sa.storylineTitle},mi=WM({fileName:ce,detail:Oi,plotIndex:si.plotIndex});mi.ok||(ft=GM(mi))}}catch{}}}catch{}}ft&&N(ft),v(tt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Ct){const Ze=Ct instanceof Error?Ct.message:"Publish failed";v(`Error: ${Ze}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return wt&&!tt},[t,Fe,M]),vt=w.useCallback(P=>{P.startsWith("_new_")&&(W(ce=>ce.filter(ye=>ye!==P)),Ke.current.delete(P),Yt.current.delete(P),fi.current.delete(P),Rt.current.delete(P),ae(ce=>{if(!(P in ce))return ce;const ye={...ce};return delete ye[P],ye}),K(ce=>{if(!(P in ce))return ce;const ye={...ce};return delete ye[P],ye}))},[]);w.useEffect(()=>{const P=ye=>{ge(new Set(ye.filter(rt=>rt.hasStructure).map(rt=>rt.name))),Pe(new Set(ye.filter(rt=>rt.hasGenesis).map(rt=>rt.name)));const Te={},De={},Le={},tt={},ft={},wt={};for(const rt of ye)Te[rt.name]=rt.contentType||"fiction",De[rt.name]=rt.language,Le[rt.name]=rt.genre,tt[rt.name]=rt.isNsfw,ft[rt.name]=rt.agentProvider,rt.title&&(wt[rt.name]=rt.title);Se(Te),Je(De),et(Le),Oe(tt),yi(ft),je(wt)};t("/api/stories").then(ye=>ye.ok?ye.json():null).then(ye=>{ye!=null&&ye.stories&&P(ye.stories)}).catch(()=>{});const ce=setInterval(async()=>{try{const ye=await t("/api/stories");if(ye.ok){const Te=await ye.json();P(Te.stories)}}catch{}},5e3);return()=>clearInterval(ce)},[t]);const At=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Bt=!!j&&!At,Ut=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const P=i;if((await t(`/api/stories/${P}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){yi(ye=>({...ye,[P]:"codex"})),K(ye=>({...ye,[P]:"codex"}));try{const ye=await t("/api/stories");if(ye.ok){const Te=await ye.json();if(Te!=null&&Te.stories){const De={};for(const Le of Te.stories)De[Le.name]=Le.agentProvider;yi(De)}}}catch{}}},[t,i]),rn=w.useCallback(P=>{i===P&&(s(null),o(null))},[i]),ri=i?oe[i]??Gt[i]:void 0,vn=Of(i,Fe,Ke.current),Wn=mM(vn,ri,i),un=!!i&&vn==="cartoon",yn=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",Sn=w.useCallback(P=>{const ce=i;if(ce)switch(P){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ee(ce,"structure.md");break;case"genesis":Ee(ce,"genesis.md");break;case"publish":h("publish");break}},[i,Ee]),fr=w.useCallback((P,ce)=>{const ye=i;if(!ye)return;const Te=De=>{$e(Le=>({action:De,seq:((Le==null?void 0:Le.seq)??0)+1}))};switch(P){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":if(!ce)return;Ee(ye,ce),Te(P);break}},[i,Ee]),pi=w.useCallback(P=>{i&&(P.genre!==void 0&&et(ce=>({...ce,[i]:P.genre||void 0})),P.language!==void 0&&Je(ce=>({...ce,[i]:P.language||void 0})),P.isNsfw!==void 0&&Oe(ce=>({...ce,[i]:P.isNsfw})))},[i]),Zt=w.useCallback(P=>{Xe(P),_e(!P)},[]),Q=kt&&!te;return d.jsxs("div",{ref:nt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Q?"stories-focused-lettering-mode":"stories-default-layout",children:[!Q&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ee,onNewStory:$,untitledSessions:A})}),!Q&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${O} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ye,onDestroySession:vt,onArchiveStory:rn,confirmedStories:de,renameRef:Ht,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Ke.current),needsProviderRepair:Wn,onRepairProvider:Vt})}),!Q&&d.jsx("div",{onMouseDown:Ue,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Q?{flex:"1 0 0"}:{flex:`${1-O} 0 0`},children:[!kt&&un&&i&&d.jsx(HM,{storyTitle:ct[i]||i,active:yn,onSelect:Sn}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:un&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:pi}):un&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:Ee}):un&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ee,onOpenStoryInfo:()=>h("story-info"),onPublish:ut,publishingFile:p,genre:at[i],language:He[i],isNsfw:jt[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:Ee}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:ut,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Ke.current)||"fiction",language:i?He[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?jt[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:P=>i&&Ee(i,P),onViewPublish:()=>h("publish"),focusedLetteringMode:kt,focusedLetteringWorkspaceVisible:te,onFocusedLetteringModeChange:Zt,onFocusedLetteringWorkspaceVisibleChange:_e,workflowActionRequest:Be,onWorkflowActionHandled:P=>$e(ce=>(ce==null?void 0:ce.seq)===P?null:ce)})}),!kt&&un&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:fr,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:he,onChange:P=>be(P.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:P=>se(P.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:P=>Y(P.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:[d.jsx("option",{value:"",children:"— Select later —"}),cl.map(P=>d.jsx("option",{value:P,children:P},P))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:P=>U(P.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:ns.map(P=>d.jsx("option",{value:P,children:P},P))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:P=>z(P.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:q,onChange:P=>xe(P.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:q==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!he.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>we("fiction",V,T,q),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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>we("cartoon",V,T,"codex"),disabled:Bt||!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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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."})]}),j&&!j.codex.installed&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Ut,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>re(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{zp as M,jo as a,$S as b,$D as c,$3 as d,No as l,ym as s,YS as t,n4 as v}; +Publish now?`;if(!window.confirm(Ee))return}const ne=wi?Ht:null;ne?await(s==null?void 0:s(e,t,K,ge,ze,ne))&&(ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(je=>(je&&URL.revokeObjectURL(je),null)),ai.current&&(ai.current.value="")):s==null||s(e,t,K,ge,ze)},disabled:!!a||br||_r||Yn||wi&&(!K||!ge)||Xi&&we!=="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"}),wi&&c==="cartoon"&&(!K||!ge)&&d.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"}),wi&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),wi&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),br&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Xi&&we==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Xi&&we==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Xi&&we==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",tt," of ",it," ","still need an uploaded image"]})]}),us&&d.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 →"}),ds.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:ds.warnings.map((ne,Ee)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ne},Ee))}),wi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ze,onChange:ne=>{Fe(ne.target.checked),cs({isNsfw:ne.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),ze&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,O]=w.useState("cartoon"),[I,A]=w.useState("unknown"),[q,R]=w.useState(!1),[re,ue]=w.useState(!1),[ye,B]=w.useState(null),[se,$]=w.useState(!1),[G,V]=w.useState(null),[H,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),ue(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&rs.find(he=>he.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),O(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const F=w.useCallback(async()=>{R(!0),ue(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)ue(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){$(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(ze){B(ze instanceof Error?ze.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",he=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",he);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!De.ok){const ze=await De.json().catch(()=>({}));B(ze.error||"Cover import failed.");return}A("present"),V(ze=>(ze&&URL.revokeObjectURL(ze),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{$(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;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.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),ue(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),ue(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),ol.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),rs.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("button",{type:"button",onClick:j,"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:H?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),ue(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:F,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"}),re&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var it,Nt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[O,I]=w.useState(null),[A,q]=w.useState(null),[R,re]=w.useState(null),[ue,ye]=w.useState(null),B=async()=>{try{const Be=await t(`/api/stories/${e}/cover-asset`),ct=Be.ok?await Be.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const qt=await Te.blob();return new File([qt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||qt.type})}catch{return null}};w.useEffect(()=>{let Be=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),qt=Te.ok?await Te.json():null;if(Be)return;!qt||!Array.isArray(qt.episodes)?(N(!0),x(null)):x(qt),v(!1)}catch{Be||(N(!0),x(null),v(!1))}})(),()=>{Be=!0}},[e,t,f]);const se=((Nt=(it=_==null?void 0:_.episodes)==null?void 0:it.find(Be=>!Be.published))==null?void 0:Nt.file)??null,$=se==="genesis.md",G=JSON.stringify([se??"",f]),[V,H]=w.useState(null);if(V!==G&&(H(G),I(null),q(null),re(null),ye(null)),w.useEffect(()=>{if(!se)return;let Be=!1;const ct=se.replace(/\.md$/,"");return(async()=>{var Te;try{const qt=[t(`/api/stories/${e}/${se}`),t(`/api/stories/${e}/cuts/${ct}`)];$&&qt.push(t(`/api/stories/${e}/structure.md`));const[yi,Ct,Je]=await Promise.all(qt);if(Be)return;if(I(yi.ok?(await yi.json()).content??"":""),Ct.ok){const ee=await Ct.json();if(Be)return;q(Array.isArray(ee.cuts)?ee.cuts:[]),re(typeof ee.title=="string"?ee.title:null)}else q(null),re(null);ye($&&Je&&Je.ok?((Te=await Je.json())==null?void 0:Te.content)??null:null)}catch{Be||(I(""),q(null),re(null),ye(null))}})(),()=>{Be=!0}},[se,$,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Be=>!Be.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=T.cuts,F=_.cover==="present",xe=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:F?"done":"todo",detail:F?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=O!==null,oe=ae?Nm({fileName:T.file,fileContent:O??"",storySlug:e,structureContent:ue,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Ho(oe,T.file),he=!X&&ae&&!Em({fileContent:O??"",episodeTitle:R}),ge=K||he,De=X&&ae?wm(O??""):null,ze=!!De&&De.blockers.length>0,Fe=!X&&ae&&A!==null?XS(O??"",A):null,we=Fe&&Fe.stage==="error"?Fe.issues:[],tt=j&&C&&(ae&&(X||A!==null))&&!ge&&!ze&&!Z&&!!a,st=async()=>{if(!(!tt||!a)){E(null);try{const Be=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Be)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Be,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Be.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Be.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Be.status==="done"?"✓":"○"}),d.jsx("span",{className:Be.status==="done"?"text-foreground":"text-muted",children:Be.label}),Be.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Be.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.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&&d.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":ze?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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((Be,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Be},`b-${ct}`)),De.warnings.map((Be,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Be},`w-${ct}`))]}),we.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(we).map(Be=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Be.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Be.title})},Be.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:we.map((Be,ct)=>d.jsx("li",{className:"font-mono break-words",children:Be},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!F&&d.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)"}),X&&!C&&d.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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.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 ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:st,disabled:!tt,"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:tt?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||ze?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:ze?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.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 qM(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 WM(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?Ho(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=qM(i,s);return a?Ho(a,t)||Ip(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,If=224,Hf=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[O,I]=w.useState(VM),[A,q]=w.useState([]),[R,re]=w.useState(!1),[ue,ye]=w.useState(""),[B,se]=w.useState(""),[$,G]=w.useState(""),[V,H]=w.useState("English"),[T,z]=w.useState("normal"),[F,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[he,ge]=w.useState(new Set),[De,ze]=w.useState(new Set),[Fe,we]=w.useState({}),[He,tt]=w.useState({}),[st,it]=w.useState({}),[Nt,Be]=w.useState({}),[ct,Te]=w.useState({}),[qt,yi]=w.useState({}),[Ct,Je]=w.useState(!1),[ee,be]=w.useState(!0),[Me,$e]=w.useState(null),Xe=w.useRef(new Map),Wt=w.useRef(new Map),pi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Gt=w.useRef(0),ot=w.useRef(null),Ht=w.useRef(null),U=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(Y=>Y.ok?Y.json():null).then(Y=>{Y!=null&&Y.address&&E(Y.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(Y=>Y.ok?Y.json():null).then(Y=>{Y&&D(Y)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(O))}catch{}},[O]),w.useEffect(()=>{const Y=()=>{if(!Ht.current)return;const me=Ht.current.getBoundingClientRect().width-If-Hf;I(_e=>jy(_e,me))};return window.addEventListener("resize",Y),Y(),()=>window.removeEventListener("resize",Y)},[]);const Ce=w.useCallback(()=>{ye(""),se(""),G(""),z("normal"),xe("claude"),re(!0)},[]),Ae=w.useCallback(async(Y,me,_e,Oe)=>{const Pe=ue.trim();if(!Pe)return;const qe=Y==="cartoon"?"codex":Oe;try{const wt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Pe,description:B.trim()||void 0,language:me,genre:$||void 0,contentType:Y,agentMode:_e,agentProvider:qe})});if(!wt.ok)return;const vt=await wt.json();re(!1),we(jt=>({...jt,[vt.name]:Y})),tt(jt=>({...jt,[vt.name]:me})),$&&it(jt=>({...jt,[vt.name]:$})),K(jt=>({...jt,[vt.name]:qe})),_e==="bypass"&&ae(jt=>({...jt,[vt.name]:!0})),s(vt.name),o(null)}catch{}},[t,ue,B,$]);w.useEffect(()=>{if(A.length===0)return;const Y=setInterval(async()=>{try{const me=await t("/api/stories");if(!me.ok)return;const _e=await me.json(),Oe=new Set(_e.stories.filter(Pe=>Pe.name!=="_example").map(Pe=>Pe.name));for(const Pe of Oe)if(!St.current.has(Pe)&&A.length>0){const qe=A[0],wt=Xe.current.get(qe)||"fiction",vt=Wt.current.get(qe)||"English",jt=pi.current.get(qe)||"normal",Ze=Rt.current.get(qe)||"claude";let Qe=!1;ot.current&&(Qe=await ot.current(qe,Pe,{contentType:wt,language:vt,agentMode:jt,agentProvider:Ze}).catch(()=>!1)),Qe&&(q(Vt=>Vt.slice(1)),Xe.current.delete(qe),Wt.current.delete(qe),pi.current.delete(qe),Rt.current.delete(qe),jt==="bypass"&&ae(Vt=>{const Ri={...Vt,[Pe]:!0};return delete Ri[qe],Ri}),K(Vt=>{const Ri={...Vt,[Pe]:Ze};return delete Ri[qe],Ri}),t(`/api/stories/${Pe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:wt,language:vt,agentMode:jt,agentProvider:Ze})}).catch(()=>{})),s(Pe),o(null)}St.current=Oe}catch{}},3e3);return()=>clearInterval(Y)},[t,A]),w.useEffect(()=>{t("/api/stories").then(Y=>{if(Y.ok)return Y.json()}).then(Y=>{Y!=null&&Y.stories&&(St.current=new Set(Y.stories.filter(me=>me.name!=="_example").map(me=>me.name)))}).catch(()=>{})},[t]);const Ne=w.useCallback((Y,me)=>{s(Y),o(me),h(null)},[]),Ge=w.useRef(null),Ue=w.useCallback(async Y=>{var me,_e,Oe,Pe;Ge.current=Y,s(Y),o(null),h(null);try{const qe=await t(`/api/stories/${Y}`);if(qe.ok&&Ge.current===Y){const wt=await qe.json();if(wt.contentType==="cartoon")return;const vt=wt.files||[],Ze=((me=vt.map(Qe=>{var Vt;return{file:Qe.file,num:(Vt=Qe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Vt[1]}}).filter(Qe=>Qe.num!=null).sort((Qe,Vt)=>parseInt(Vt.num)-parseInt(Qe.num))[0])==null?void 0:me.file)??((_e=vt.find(Qe=>Qe.file==="genesis.md"))==null?void 0:_e.file)??((Oe=vt.find(Qe=>Qe.file==="structure.md"))==null?void 0:Oe.file)??((Pe=vt[0])==null?void 0:Pe.file);Ze&&Ge.current===Y&&o(Ze)}}catch{}},[t]),dt=w.useCallback(Y=>{Y.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const me=Oe=>{if(!U.current||!Ht.current)return;const Pe=Ht.current.getBoundingClientRect(),qe=Pe.width-If-Hf,wt=Oe.clientX-Pe.left-If;I(jy(wt/qe,qe))},_e=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",_e)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",_e)},[]),_t=w.useCallback(async(Y,me,_e,Oe,Pe,qe)=>{var Ze;f(me),v("Reading file..."),N(null);let wt=!1,vt=null,jt=!1;try{const Qe=await t(`/api/stories/${Y}/${me}`);if(!Qe.ok)throw new Error("Failed to read file");const Vt=await Qe.json(),Ri=Fe[Y];let Kt=null,Jt=null;if(me==="genesis.md")try{const Xt=await t(`/api/stories/${Y}/structure.md`);Xt.ok&&(Kt=(await Xt.json()).content??null)}catch{}else if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/))try{const Xt=await t(`/api/stories/${Y}/cuts/${me.replace(/\.md$/,"")}`);Xt.ok&&(Jt=(await Xt.json()).title??null)}catch{}const Gn=Nm({fileName:me,fileContent:Vt.content,storySlug:Y,structureContent:Kt,contentType:Ri,episodeTitle:Jt});if(Ri==="cartoon"&&Ho(Gn,me))return v(me==="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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/)&&!Em({fileContent:Vt.content,episodeTitle:Jt}))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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me==="genesis.md"){const Xt=wm(Vt.content).blockers;if(Xt.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Xt[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Dn;if(me.match(/^plot-\d+\.md$/)){if(pM(Vt)){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(()=>{f(null),v("")},6e3);return}try{const Xt=await t(`/api/stories/${Y}`);if(Xt.ok){const Di=(await Xt.json()).files.find(or=>or.file==="genesis.md"&&or.storylineId);Dn=Di==null?void 0:Di.storylineId}}catch{}if(!Dn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Xt=await t("/api/publish/preflight");if(Xt.ok){const Ii=await Xt.json();if(gM(Ii))return N(xM(Ii)),f(null),v(""),!1}}catch{}v("Publishing...");const Br=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:Y,fileName:me,title:Gn,content:Vt.content,genre:_e,language:Oe,isNsfw:Pe,storylineId:Dn,...wy(Fe,Y,Dn)?{contentType:wy(Fe,Y,Dn)}:{}})});if(!Br.ok){const Xt=await Br.json();throw new Error(Xt.error||"Publish failed")}const cs=(Ze=Br.body)==null?void 0:Ze.getReader(),gr=new TextDecoder;if(cs)for(;;){const{done:Xt,value:Ii}=await cs.read();if(Xt)break;const or=gr.decode(Ii).split(` +`).filter(Gs=>Gs.startsWith("data: "));for(const Gs of or)try{const ei=JSON.parse(Gs.slice(6));if(ei.step&&v(ei.message||ei.step),ei.step==="done"&&ei.txHash){if(jt=!0,await t(`/api/stories/${Y}/${me}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:ei.txHash,storylineId:ei.storylineId,plotIndex:ei.plotIndex,contentCid:ei.contentCid,gasCost:ei.gasCost,indexError:ei.indexError,authorAddress:M})}),x(Mn=>Mn+1),qe&&me==="genesis.md"&&ei.storylineId){v("Uploading cover...");let Mn=null;try{Mn=await uM(t,ei.storylineId,qe)}catch{}Mn||(wt=!0)}if(Ri==="cartoon"&&ei.storylineId)try{const Mn=me!=="genesis.md",Lr=`storylineId=${ei.storylineId}`+(Mn&&ei.plotIndex!=null?`&plotIndex=${ei.plotIndex}`:""),xl=await t(`/api/publish/public-title?${Lr}`);if(xl.ok){const Si=await xl.json(),wi=Mn?{plots:Si.plotTitle!=null?[{plotIndex:ei.plotIndex,title:Si.plotTitle}]:[]}:{title:Si.storylineTitle},Bn=WM({fileName:me,detail:wi,plotIndex:ei.plotIndex});Bn.ok||(vt=GM(Bn))}}catch{}}}catch{}}vt&&N(vt),v(wt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Qe){const Vt=Qe instanceof Error?Qe.message:"Publish failed";v(`Error: ${Vt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return jt&&!wt},[t,Fe,M]),At=w.useCallback(Y=>{Y.startsWith("_new_")&&(q(me=>me.filter(_e=>_e!==Y)),Xe.current.delete(Y),Wt.current.delete(Y),pi.current.delete(Y),Rt.current.delete(Y),ae(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}),K(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}))},[]);w.useEffect(()=>{const Y=_e=>{ge(new Set(_e.filter(Ze=>Ze.hasStructure).map(Ze=>Ze.name))),ze(new Set(_e.filter(Ze=>Ze.hasGenesis).map(Ze=>Ze.name)));const Oe={},Pe={},qe={},wt={},vt={},jt={};for(const Ze of _e)Oe[Ze.name]=Ze.contentType||"fiction",Pe[Ze.name]=Ze.language,qe[Ze.name]=Ze.genre,wt[Ze.name]=Ze.isNsfw,vt[Ze.name]=Ze.agentProvider,Ze.title&&(jt[Ze.name]=Ze.title);we(Oe),tt(Pe),it(qe),Be(wt),yi(vt),Te(jt)};t("/api/stories").then(_e=>_e.ok?_e.json():null).then(_e=>{_e!=null&&_e.stories&&Y(_e.stories)}).catch(()=>{});const me=setInterval(async()=>{try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();Y(Oe.stories)}}catch{}},5e3);return()=>clearInterval(me)},[t]);const Bt=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Ut=!!j&&!Bt,Yt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),an=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const Y=i;if((await t(`/api/stories/${Y}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){yi(_e=>({..._e,[Y]:"codex"})),K(_e=>({..._e,[Y]:"codex"}));try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();if(Oe!=null&&Oe.stories){const Pe={};for(const qe of Oe.stories)Pe[qe.name]=qe.agentProvider;yi(Pe)}}}catch{}}},[t,i]),ai=w.useCallback(Y=>{i===Y&&(s(null),o(null))},[i]),An=i?oe[i]??qt[i]:void 0,Rn=Of(i,Fe,Xe.current),lr=mM(Rn,An,i),Pi=!!i&&Rn==="cartoon",vn=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",mr=w.useCallback(Y=>{const me=i;if(me)switch(Y){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ne(me,"structure.md");break;case"genesis":Ne(me,"genesis.md");break;case"publish":h("publish");break}},[i,Ne]),mi=w.useCallback((Y,me)=>{const _e=i;if(!_e)return;const Oe=Pe=>{Gt.current+=1,$e({action:Pe,seq:Gt.current})};switch(Y){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":if(!me)return;Ne(_e,me),Oe(Y);break}},[i,Ne]),Qt=w.useCallback(Y=>{i&&(Y.genre!==void 0&&it(me=>({...me,[i]:Y.genre||void 0})),Y.language!==void 0&&tt(me=>({...me,[i]:Y.language||void 0})),Y.isNsfw!==void 0&&Be(me=>({...me,[i]:Y.isNsfw})))},[i]),te=w.useCallback(Y=>{Je(Y),be(!Y)},[]),ve=Ct&&!ee;return d.jsxs("div",{ref:Ht,className:"h-[calc(100vh-3.5rem)] flex","data-testid":ve?"stories-focused-lettering-mode":"stories-default-layout",children:[!ve&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ne,onNewStory:Ce,untitledSessions:A})}),!ve&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${O} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ue,onDestroySession:At,onArchiveStory:ai,confirmedStories:he,renameRef:ot,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Xe.current),needsProviderRepair:lr,onRepairProvider:an})}),!ve&&d.jsx("div",{onMouseDown:dt,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:ve?{flex:"1 0 0"}:{flex:`${1-O} 0 0`},children:[!Ct&&Pi&&i&&d.jsx(HM,{storyTitle:ct[i]||i,active:vn,onSelect:mr}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:Pi&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:Qt}):Pi&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:Ne}):Pi&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ne,onOpenStoryInfo:()=>h("story-info"),onPublish:_t,publishingFile:p,genre:st[i],language:He[i],isNsfw:Nt[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:Ne}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:_t,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Xe.current)||"fiction",language:i?He[i]:void 0,genre:i?st[i]:void 0,isNsfw:i?Nt[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:Y=>i&&Ne(i,Y),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:ee,onFocusedLetteringModeChange:te,onFocusedLetteringWorkspaceVisibleChange:be,workflowActionRequest:Me,onWorkflowActionHandled:Y=>$e(me=>(me==null?void 0:me.seq)===Y?null:me)})}),!Ct&&Pi&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:mi,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:ue,onChange:Y=>ye(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:Y=>se(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:$,onChange:Y=>G(Y.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:[d.jsx("option",{value:"",children:"— Select later —"}),ol.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:Y=>H(Y.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:rs.map(Y=>d.jsx("option",{value:Y,children:Y},Y))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:Y=>z(Y.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:F,onChange:Y=>xe(Y.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:F==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!ue.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>Ae("fiction",V,T,F),disabled:!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>Ae("cartoon",V,T,"codex"),disabled:Ut||!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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."})]}),j&&!j.codex.installed&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Yt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>re(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{zp as M,jo as a,$S as b,$D as c,$3 as d,No as l,ym as s,YS as t,n4 as v}; diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 7650250..454f503 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,7 +7,7 @@ - + From 9a918b1c9eedf02be195d8351692e43f910a311c Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:21:00 +0000 Subject: [PATCH 4/4] Preserve Genesis cuts mode for CTA requests --- app/web/components/PreviewPanel.tsx | 13 +++- ...cut-33MiJugN.js => export-cut-BeffiHI_.js} | 2 +- .../{index-Ce_xoof_.js => index-CuMJdtXy.js} | 78 +++++++++---------- app/web/dist/index.html | 2 +- 4 files changed, 53 insertions(+), 42 deletions(-) rename app/web/dist/assets/{export-cut-33MiJugN.js => export-cut-BeffiHI_.js} (98%) rename app/web/dist/assets/{index-Ce_xoof_.js => index-CuMJdtXy.js} (82%) diff --git a/app/web/components/PreviewPanel.tsx b/app/web/components/PreviewPanel.tsx index f29c688..7ae1030 100644 --- a/app/web/components/PreviewPanel.tsx +++ b/app/web/components/PreviewPanel.tsx @@ -140,6 +140,13 @@ interface FileData { type Tab = "preview" | "edit"; +function workflowActionNeedsCuts(action: CoachUiAction | null | undefined): boolean { + return action === "open-cuts" + || action === "open-lettering" + || action === "upload" + || action === "refresh-assets"; +} + export function PreviewPanel({ storyName, fileName, @@ -276,6 +283,10 @@ export function PreviewPanel({ const prevFileRef = useRef(null); const appliedWorkflowSeqRef = useRef(0); + const pendingWorkflowCutsRef = useRef(false); + pendingWorkflowCutsRef.current = workflowActionNeedsCuts( + workflowActionRequest?.action, + ); const loadFile = useCallback(async () => { if (!storyName || !fileName) { @@ -806,7 +817,7 @@ export function PreviewPanel({ setDetectedCoverWarning(null); setCoverStatus("unknown"); coverUserTouchedRef.current = false; - setGenesisEditMode("text"); + setGenesisEditMode(pendingWorkflowCutsRef.current ? "cuts" : "text"); }, [storyName, fileName]); // Auto-detect an agent-created cover (assets/cover.webp|jpg) for an UNPUBLISHED diff --git a/app/web/dist/assets/export-cut-33MiJugN.js b/app/web/dist/assets/export-cut-BeffiHI_.js similarity index 98% rename from app/web/dist/assets/export-cut-33MiJugN.js rename to app/web/dist/assets/export-cut-BeffiHI_.js index 7622dfb..821f51b 100644 --- a/app/web/dist/assets/export-cut-33MiJugN.js +++ b/app/web/dist/assets/export-cut-BeffiHI_.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-Ce_xoof_.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-CuMJdtXy.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-Ce_xoof_.js b/app/web/dist/assets/index-CuMJdtXy.js similarity index 82% rename from app/web/dist/assets/index-Ce_xoof_.js rename to app/web/dist/assets/index-CuMJdtXy.js index def67ae..c4161d5 100644 --- a/app/web/dist/assets/index-Ce_xoof_.js +++ b/app/web/dist/assets/index-CuMJdtXy.js @@ -1,4 +1,4 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Pu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vd={exports:{}},oo={};/** +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Pu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vd={exports:{}},co={};/** * @license React * react-jsx-runtime.production.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 ib;function pC(){if(ib)return oo;ib=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 oo.Fragment=t,oo.jsx=i,oo.jsxs=i,oo}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={exports:{}},et={};/** + */var ib;function pC(){if(ib)return co;ib=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 co.Fragment=t,co.jsx=i,co.jsxs=i,co}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={exports:{}},tt={};/** * @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 rb;function gC(){if(rb)return et;rb=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"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,M={};function E(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,X){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,X,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function O(){}O.prototype=E.prototype;function I(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}var A=I.prototype=new O;A.constructor=I,N(A,E.prototype),A.isPureReactComponent=!0;var q=Array.isArray;function R(){}var re={H:null,A:null,T:null,S:null},ue=Object.prototype.hasOwnProperty;function ye(D,X,C){var Z=C.ref;return{$$typeof:e,type:D,key:X,ref:Z!==void 0?Z:null,props:C}}function B(D,X){return ye(D.type,X,D.props)}function se(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function $(D){var X={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(C){return X[C]})}var G=/\/+/g;function V(D,X){return typeof D=="object"&&D!==null&&D.key!=null?$(""+D.key):X.toString(36)}function H(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(R,R):(D.status="pending",D.then(function(X){D.status==="pending"&&(D.status="fulfilled",D.value=X)},function(X){D.status==="pending"&&(D.status="rejected",D.reason=X)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function T(D,X,C,Z,ae){var oe=typeof D;(oe==="undefined"||oe==="boolean")&&(D=null);var K=!1;if(D===null)K=!0;else switch(oe){case"bigint":case"string":case"number":K=!0;break;case"object":switch(D.$$typeof){case e:case t:K=!0;break;case _:return K=D._init,T(K(D._payload),X,C,Z,ae)}}if(K)return ae=ae(D),K=Z===""?"."+V(D,0):Z,q(ae)?(C="",K!=null&&(C=K.replace(G,"$&/")+"/"),T(ae,X,C,"",function(De){return De})):ae!=null&&(se(ae)&&(ae=B(ae,C+(ae.key==null||D&&D.key===ae.key?"":(""+ae.key).replace(G,"$&/")+"/")+K)),X.push(ae)),1;K=0;var he=Z===""?".":Z+":";if(q(D))for(var ge=0;ge>>1,j=T[xe];if(0>>1;xea(C,F))Za(ae,C)?(T[xe]=ae,T[Z]=F,xe=Z):(T[xe]=C,T[X]=F,xe=X);else if(Za(ae,F))T[xe]=ae,T[Z]=F,xe=Z;else break e}}return z}function a(T,z){var F=T.sortIndex-z.sortIndex;return F!==0?F:T.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,$());else{var z=i(f);z!==null&&H(q,z.startTime-T)}}var R=!1,re=-1,ue=5,ye=-1;function B(){return M?!0:!(e.unstable_now()-yeT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&H(q,D.startTime-T),z=!1}}break e}finally{x=null,b=F,v=!1}z=void 0}}finally{z?$():R=!1}}}var $;if(typeof I=="function")$=function(){I(se)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,V=G.port2;G.port1.onmessage=se,$=function(){V.postMessage(null)}}else $=function(){E(se,0)};function H(T,z){re=E(function(){T(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(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=F,t(f,T),i(p)===null&&T===i(f)&&(N?(O(re),re=-1):N=!0,H(q,F-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,$()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var F=b;b=z;try{return T.apply(this,arguments)}finally{b=F}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},ln={};/** + */var ab;function _C(){return ab||(ab=1,(function(e){function t(T,z){var F=T.length;T.push(z);e:for(;0>>1,j=T[xe];if(0>>1;xea(C,F))Za(ae,C)?(T[xe]=ae,T[Z]=F,xe=Z):(T[xe]=C,T[X]=F,xe=X);else if(Za(ae,F))T[xe]=ae,T[Z]=F,xe=Z;else break e}}return z}function a(T,z){var F=T.sortIndex-z.sortIndex;return F!==0?F:T.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,$());else{var z=i(f);z!==null&&H(q,z.startTime-T)}}var R=!1,ne=-1,ue=5,ye=-1;function B(){return M?!0:!(e.unstable_now()-yeT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&H(q,D.startTime-T),z=!1}}break e}finally{x=null,b=F,v=!1}z=void 0}}finally{z?$():R=!1}}}var $;if(typeof I=="function")$=function(){I(re)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,V=G.port2;G.port1.onmessage=re,$=function(){V.postMessage(null)}}else $=function(){E(re,0)};function H(T,z){ne=E(function(){T(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(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=F,t(f,T),i(p)===null&&T===i(f)&&(N?(L(ne),ne=-1):N=!0,H(q,F-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,$()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var F=b;b=z;try{return T.apply(this,arguments)}finally{b=F}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},ln={};/** * @license React * react-dom.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 ub;function SC(){if(ub)return co;ub=1;var e=bC(),t=$p(),i=yC();function s(n){var r="https://react.dev/errors/"+n;if(1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function he(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function De(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function ze(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),ro._currentValue=F)}var Fe,we;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",we=-1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function he(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function De(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function ze(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),so._currentValue=F)}var Fe,we;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",we=-1)":-1m||L[u]!==J[m]){var ce=` -`+L[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{tt=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function it(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return st(n.type,!1);case 11:return st(n.type.render,!1);case 1:return st(n.type,!0);case 31:return He("Activity");default:return""}}function Nt(n){try{var r="",l=null;do r+=it(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`);for(m=u=0;um||O[u]!==J[m]){var ce=` +`+O[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{it=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function nt(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return st(n.type,!1);case 11:return st(n.type.render,!1);case 1:return st(n.type,!0);case 31:return He("Activity");default:return""}}function Nt(n){try{var r="",l=null;do r+=nt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Be=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,qt=e.unstable_shouldYield,yi=e.unstable_requestPaint,Ct=e.unstable_now,Je=e.unstable_getCurrentPriorityLevel,ee=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Me=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Xe=e.unstable_IdlePriority,Wt=e.log,pi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Gt(n){if(typeof Wt=="function"&&pi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var ot=Math.clz32?Math.clz32:Ce,Ht=Math.log,U=Math.LN2;function Ce(n){return n>>>=0,n===0?32:31-(Ht(n)/U|0)|0}var Ae=256,Ne=262144,Ge=4194304;function Ue(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(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 _t(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(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 Bt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Yt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function an(n,r,l,u,m,g){var y=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,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var xl=/[\n"\\]/g;function Si(n){return n.replace(xl,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function wi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Di(r)):n.value!==""+Di(r)&&(n.value=""+Di(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Xi(n,y,Di(r)):l!=null?Xi(n,y,Di(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=""+Di(k):n.removeAttribute("name")}function Bn(n,r,l,u,m,g,y,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)){ei(n);return}l=l!=null?""+Di(l):"",r=r!=null?""+Di(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),ei(n)}function Xi(n,r,l){r==="number"&&Lr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Zi(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"),ds=!1;if(cr)try{var fs={};Object.defineProperty(fs,"passive",{get:function(){ds=!0}}),window.addEventListener("test",fs,fs),window.removeEventListener("test",fs,fs)}catch{ds=!1}var ne=null,Ee=null,je=null;function nt(){if(je)return je;var n,r=Ee,l=r.length,u,m="value"in ne?ne.value:ne.textContent,g=m.length;for(n=0;n=kl),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var wa=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(wa)return n==="compositionend"||!eh&&Bm(n,r)?(n=nt(),je=Ee=ne=null,wa=!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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=Lr(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=Lr(n.document)}return r}function nh(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 Y1=cr&&"documentMode"in document&&11>=document.documentMode,Ca=null,rh=null,Tl=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||Ca==null||Ca!==Lr(u)||(u=Ca,"selectionStart"in u&&nh(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}),Tl&&jl(Tl,u)||(Tl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-ot(r)+m|l<at?(xt=Ie,Ie=null):xt=Ie.sibling;var Et=ie(W,Ie,Q[at],de);if(Et===null){Ie===null&&(Ie=xt);break}n&&Ie&&Et.alternate===null&&r(W,Ie),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et,Ie=xt}if(at===Q.length)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;atat?(xt=Ie,Ie=null):xt=Ie.sibling;var Ls=ie(W,Ie,Et.value,de);if(Ls===null){Ie===null&&(Ie=xt);break}n&&Ie&&Ls.alternate===null&&r(W,Ie),P=g(Ls,P,at),kt===null?We=Ls:kt.sibling=Ls,kt=Ls,Ie=xt}if(Et.done)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;!Et.done;at++,Et=Q.next())Et=fe(W,Et.value,de),Et!==null&&(P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return bt&&Ur(W,at),We}for(Ie=u(Ie);!Et.done;at++,Et=Q.next())Et=le(Ie,W,at,Et.value,de),Et!==null&&(n&&Et.alternate!==null&&Ie.delete(Et.key===null?at:Et.key),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return n&&Ie.forEach(function(fC){return r(W,fC)}),bt&&Ur(W,at),We}function Pt(W,P,Q,de){if(typeof Q=="object"&&Q!==null&&Q.type===N&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case v:e:{for(var We=Q.key;P!==null;){if(P.key===We){if(We=Q.type,We===N){if(P.tag===7){l(W,P.sibling),de=m(P,Q.props.children),de.return=W,W=de;break e}}else if(P.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===ue&&ia(We)===P.type){l(W,P.sibling),de=m(P,Q.props),Ll(de,Q),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Q.type===N?(de=Zs(Q.props.children,W.mode,de,Q.key),de.return=W,W=de):(de=rc(Q.type,Q.key,Q.props,null,W.mode,de),Ll(de,Q),de.return=W,W=de)}return y(W);case S:e:{for(We=Q.key;P!==null;){if(P.key===We)if(P.tag===4&&P.stateNode.containerInfo===Q.containerInfo&&P.stateNode.implementation===Q.implementation){l(W,P.sibling),de=m(P,Q.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Q,W.mode,de),de.return=W,W=de}return y(W);case ue:return Q=ia(Q),Pt(W,P,Q,de)}if(H(Q))return Le(W,P,Q,de);if($(Q)){if(We=$(Q),typeof We!="function")throw Error(s(150));return Q=We.call(Q),Ve(W,P,Q,de)}if(typeof Q.then=="function")return Pt(W,P,hc(Q),de);if(Q.$$typeof===I)return Pt(W,P,lc(W,Q),de);dc(W,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Q),de.return=W,W=de):(l(W,P),de=hh(Q,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Q,de){try{Bl=0;var We=Pt(W,P,Q,de);return La=null,We}catch(Ie){if(Ie===Ba||Ie===cc)throw Ie;var kt=On(29,Ie,null,W.mode);return kt.lanes=de,kt.return=W,kt}finally{}}}var ra=gg(!0),xg=gg(!1),_s=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 bs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function vs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ol(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,An(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function zl(){if(Nh){var n=Ma;if(n!==null)throw n}}function Pl(n,r,l,u){Nh=!1;var m=n.updateQueue;_s=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==y&&(k===null?ce.firstBaseUpdate=J:k.next=J,ce.lastBaseUpdate=L))}if(g!==null){var fe=m.baseState;y=0,ce=J=L=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(gt&ie)===ie:(u&ie)===ie){ie!==0&&ie===Da&&(Nh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Le=n,Ve=k;ie=r;var Pt=l;switch(Ve.tag){case 1:if(Le=Ve.payload,typeof Le=="function"){fe=Le.call(Pt,fe,ie);break e}fe=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ve.payload,ie=typeof Le=="function"?Le.call(Pt,fe,ie):Le,ie==null)break e;fe=x({},fe,ie);break e;case 2:_s=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(J=ce=le,L=fe):ce=ce.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ce===null&&(L=fe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),ks|=y,n.lanes=y,n.memoizedState=fe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var L=m(),J=T.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ce=iw(L,u);Ul(n,r,ce,Un(n))}else Ul(n,r,u,Un(n))}catch(fe){Ul(n,r,{then:function(){},status:"rejected",reason:fe},Un())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,F,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:F},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),Ul(n,r.next.queue,{},Un())}function Wh(){return Ji(ro)}function Jg(){return bi().memoizedState}function ex(){return bi().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Un();n=bs(l);var u=vs(r,n,l);u!==null&&(kn(u,r,l),Ol(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Un();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(kn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Un();Ul(n,r,l,u)}function Ul(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Ln(k,y))return ic(n,r,m,0),$t===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return kn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&kn(r,n,2)}function Sc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function ix(n,r){za=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,An(n,l)}}var $l={readContext:Ji,use:_c,useCallback:ci,useContext:ci,useEffect:ci,useImperativeHandle:ci,useLayoutEffect:ci,useInsertionEffect:ci,useMemo:ci,useReducer:ci,useRef:ci,useState:ci,useDebugValue:ci,useDeferredValue:ci,useTransition:ci,useSyncExternalStore:ci,useId:ci,useHostTransitionStatus:ci,useFormState:ci,useActionState:ci,useOptimistic:ci,useMemoCache:ci,useCacheRefresh:ci};$l.useEffectEvent=ci;var rx={readContext:Ji,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Gt(!0);try{n()}finally{Gt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Gt(!0);try{l(r)}finally{Gt(!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=uw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,rt,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),$t===null)throw Error(s(349));(gt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,Ia(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=$t.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-ot(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Qt]=r,g[te]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(tn(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&&Yr(r)}}return ii(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Yr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Aa(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Qt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||gs(r,!0)}else n=$c(n).createTextNode(u),n[Qt]=r,r.stateNode=n}return ii(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Aa(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[Qt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Pn(r),r):(Pn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return ii(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Aa(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[Qt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Pn(r),r):(Pn(r),null)}return Pn(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),Nc(r,r.updateQueue),ii(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),ii(r),null;case 10:return Fr(r.type),ii(r),null;case 19:if(X(_i),u=r.memoizedState,u===null)return ii(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)ql(u,!1);else{if(ui!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,ql(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(_i,_i.current&1|2),bt&&Ur(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Dc&&(r.flags|=128,m=!0,ql(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),ql(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return ii(r),null}else 2*Ct()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,ql(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=Ct(),n.sibling=null,l=_i.current,C(_i,m?l&1|2:l&1),bt&&Ur(r,u.treeForkCount),n):(ii(r),null);case 22:case 23:return Pn(r),Th(),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&&(ii(r),r.subtreeFlags&6&&(r.flags|=8192)):ii(r),l=r.updateQueue,l!==null&&Nc(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&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Fr(Ci),ii(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Fr(Ci),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return ze(r),null;case 31:if(r.memoizedState!==null){if(Pn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Pn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(_i),null;case 4:return ge(),null;case 10:return Fr(r.type),null;case 22:case 23:return Pn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Fr(Ci),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:Fr(Ci),ge();break;case 26:case 27:case 5:ze(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&Pn(r);break;case 13:Pn(r);break;case 19:X(_i);break;case 10:Fr(r.type);break;case 22:case 23:Pn(r),Th(),n!==null&&X(ta);break;case 24:Fr(Ci)}}function Wl(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function ws(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ce){Mt(m,L,ce)}}}u=u.next}while(u!==g)}}catch(ce){Mt(r,r.return,ce)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Gl(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){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(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){Mt(n,r,m)}else l.current=null}function Rx(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){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[te]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&As(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&As(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 cd(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=Yn));else if(u!==4&&(u===27&&As(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&As(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);tn(r,u,l),r[Qt]=n,r[te]=l}catch(g){Mt(n,n.return,g)}}var Vr=!1,Ni=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Hi=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(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 y=0,k=-1,L=-1,J=0,ce=0,fe=n,ie=null;t:for(;;){for(var le;fe!==l||m!==0&&fe.nodeType!==3||(k=y+m),fe!==g||u!==0&&fe.nodeType!==3||(L=y+u),fe.nodeType===3&&(y+=fe.nodeValue.length),(le=fe.firstChild)!==null;)ie=fe,fe=le;for(;;){if(fe===n)break t;if(ie===l&&++J===m&&(k=y),ie===g&&++ce===u&&(L=y),(le=fe.nextSibling)!==null)break;fe=ie,ie=fe.parentNode}fe=le}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,Hi=r;Hi!==null;)if(r=Hi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Hi=n;else for(;Hi!==null;){switch(r=Hi,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"))),tn(g,u,l),g[Qt]=n,Qe(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Pt);if(W&&P&&(le.rangeCount!==1||le.anchorNode!==W.node||le.anchorOffset!==W.offset||le.focusNode!==P.node||le.focusOffset!==P.offset)){var Q=fe.createRange();Q.setStart(W.node,W.offset),le.removeAllRanges(),Ve>Pt?(le.addRange(Q),le.extend(P.node,P.offset)):(Q.setEnd(P.node,P.offset),le.addRange(Q))}}}}for(fe=[],le=k;le=le.parentNode;)le.nodeType===1&&fe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=Ns,y=Jr;if(Mi=0,qa=Ns=null,Jr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Ql(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Kn(l,r),r=Xh(n.stateNode,r,2),n=vs(n,r,2),n!==null&&(Yt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(Es===null||!Es.has(u))){n=Kn(l,n),l=dx(2),u=vs(r,l,2),u!==null&&(fx(l,u,r,n),Yt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,$t===n&&(gt&l)===l&&(ui===4||ui===3&&(gt&62914560)===gt&&300>Ct()-Rc?(Tt&2)===0&&Wa(n,0):pd|=l,Fa===gt&&(Fa=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Yt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Ya=null,Sd=!1,Ic=!1,wd=!1,Ts=0;function Cr(n){n!==Ya&&n.next===null&&(Ya===null?Pc=Ya=n:Ya=Ya.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Ql(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-ot(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=gt,g=dt(u,u===$t?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||_t(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;Ts!==0&&Iw()&&(n=Ts);for(var r=Ct(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Ya=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Mi!==0&&Mi!==5||Ql(n),Ts!==0&&(Ts=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ce=L.transferSize,fe=L.initiatorType;ce&&C_(fe)&&(L=L.responseEnd,y+=ce*(L"u"?null:document;function O_(n,r,l){var u=Va;if(u&&typeof r=="string"&&r){var m=Si(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Vw(n){es.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){es.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){es.L(n,r,l);var u=Va;if(u&&n&&r){var m='link[rel="preload"][as="'+Si(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Si(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Si(l.imageSizes)+'"]')):m+='[href="'+Si(n)+'"]';var g=m;switch(r){case"style":g=Ka(n);break;case"script":g=Xa(n)}tr.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),tr.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(io(g))||r==="script"&&u.querySelector(no(g))||(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Zw(n,r){es.m(n,r);var l=Va;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Si(u)+'"][href="'+Si(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Xa(n)}if(!tr.has(g)&&(n=x({rel:"modulepreload",href:n},r),tr.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(no(g)))return}u=l.createElement("link"),tn(u,"link",n),Qe(u),l.head.appendChild(u)}}}function Qw(n,r,l){es.S(n,r,l);var u=Va;if(u&&n){var m=Ze(u).hoistableStyles,g=Ka(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(io(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=tr.get(g))&&Id(n,l);var L=y=u.createElement("link");Qe(L),tn(L,"link",n),L._p=new Promise(function(J,ce){L.onload=J,L.onerror=ce}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){es.X(n,r);var l=Va;if(l&&n){var u=Ze(l).hoistableScripts,m=Xa(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0},r),(r=tr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){es.M(n,r);var l=Va;if(l&&n){var u=Ze(l).hoistableScripts,m=Xa(n),g=u.get(m);g||(g=l.querySelector(no(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=tr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(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=Ka(l.href),l=Ze(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=Ka(l.href);var g=Ze(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(io(n)))&&!g._p&&(y.instance=g,y.state.loading=5),tr.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},tr.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Xa(l),l=Ze(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 Ka(n){return'href="'+Si(n)+'"'}function io(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),tn(r,"link",l),Qe(r),n.head.appendChild(r))}function Xa(n){return'[src="'+Si(n)+'"]'}function no(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Si(l.href)+'"]');if(u)return r.instance=u,Qe(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"),Qe(u),tn(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ka(l.href);var g=n.querySelector(io(m));if(g)return r.state.loading|=4,r.instance=g,Qe(g),g;u=P_(l),(m=tr.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Qe(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),tn(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Xa(l.src),(m=n.querySelector(no(g)))?(r.instance=m,Qe(m),m):(u=l,(m=tr.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Qe(m),tn(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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=Ka(u.href),g=r.querySelector(io(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Qe(g);return}g=r.ownerDocument||r,u=P_(u),(m=tr.get(m))&&Id(u,m),g=g.createElement("link"),Qe(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),tn(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,O)=>fetch(E,{...O,headers:{...O==null?void 0:O.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),O=await E.json();if(!E.ok)throw new Error(O.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const O=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await O.json();if(!O.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(O){_(O instanceof Error?O.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[O,I]=w.useState(""),[A,q]=w.useState(!1),[R,re]=w.useState(null),[ue,ye]=w.useState(""),[B,se]=w.useState(null),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(null),[F,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){re("Agent name is required");return}if(!M.trim()){re("Description is required");return}q(!0),re(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...O.trim()&&{genre:O}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){re(ae instanceof Error?ae.message:"Registration failed")}q(!1)},X=async()=>{if(!ue.trim()||!/^0x[a-fA-F0-9]{40}$/.test(ue)){H("Enter a valid wallet address (0x...)");return}G(!0),H(null),se(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:ue})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");se(oe)}catch(ae){H(ae instanceof Error?ae.message:"Failed to generate binding code")}G(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!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 ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:O,onChange:ae=>I(ae.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.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:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(F==null?void 0:F.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(F==null?void 0:F.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:F!=null&&F.codex.installed?F.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(F)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.checkedAt?new Date(F.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:ue,onChange:ae=>ye(ae.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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:$||!ue.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:$?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.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"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const re=new Set(R);return re.has(q)?re.delete(q):re.add(q),re})},O=q=>{var re;const R=q.map(ue=>{var ye;return{file:ue.file,num:(ye=ue.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(ue=>ue.num!=null).sort((ue,ye)=>parseInt(ye.num)-parseInt(ue.num));return R.length>0?R[0].file:q.some(ue=>ue.file==="genesis.md")?"genesis.md":q.some(ue=>ue.file==="structure.md")?"structure.md":((re=q[0])==null?void 0:re.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=O(q.files);R&&s(q.name,R)}},A=q=>{const R=re=>{if(re==="structure.md")return 0;if(re==="genesis.md")return 1;const ue=re.match(/^plot-(\d+)\.md$/);return ue?2+parseInt(ue[1]):100};return[...q].sort((re,ue)=>R(re.file)-R(ue.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:A(q.files).map(R=>{const re=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${re?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var Be=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Wt=e.unstable_shouldYield,vi=e.unstable_requestPaint,Ct=e.unstable_now,et=e.unstable_getCurrentPriorityLevel,ee=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Me=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Xe=e.unstable_IdlePriority,Gt=e.log,pi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Yt(n){if(typeof Gt=="function"&&pi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var ot=Math.clz32?Math.clz32:Ce,Ht=Math.log,U=Math.LN2;function Ce(n){return n>>>=0,n===0?32:31-(Ht(n)/U|0)|0}var Ae=256,Ne=262144,Ge=4194304;function Ue(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 dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(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 _t(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(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 Bt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Vt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function an(n,r,l,u,m,g){var y=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,O=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ws=/[\n"\\]/g;function Zi(n){return n.replace(Ws,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Pr(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+yi(r)):n.value!==""+yi(r)&&(n.value=""+yi(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?ur(n,y,yi(r)):l!=null?ur(n,y,yi(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=""+yi(k):n.removeAttribute("name")}function Si(n,r,l,u,m,g,y,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)){Qt(n);return}l=l!=null?""+yi(l):"",r=r!=null?""+yi(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,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Qt(n)}function ur(n,r,l){r==="number"&&zr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function wi(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"),Cl=!1;if(Sn)try{var vr={};Object.defineProperty(vr,"passive",{get:function(){Cl=!0}}),window.addEventListener("test",vr,vr),window.removeEventListener("test",vr,vr)}catch{Cl=!1}var dr=null,se=null,Ee=null;function je(){if(Ee)return Ee;var n,r=se,l=r.length,u,m="value"in dr?dr.value:dr.textContent,g=m.length;for(n=0;n=El),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ea=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(Ea)return n==="compositionend"||!eh&&Bm(n,r)?(n=je(),Ee=se=dr=null,Ea=!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=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=zr(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=zr(n.document)}return r}function nh(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 Y1=Sn&&"documentMode"in document&&11>=document.documentMode,Na=null,rh=null,Al=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||Na==null||Na!==zr(u)||(u=Na,"selectionStart"in u&&nh(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}),Al&&Tl(Al,u)||(Al=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-ot(r)+m|l<at?(xt=Ie,Ie=null):xt=Ie.sibling;var Et=ie(W,Ie,Q[at],de);if(Et===null){Ie===null&&(Ie=xt);break}n&&Ie&&Et.alternate===null&&r(W,Ie),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et,Ie=xt}if(at===Q.length)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;atat?(xt=Ie,Ie=null):xt=Ie.sibling;var Ms=ie(W,Ie,Et.value,de);if(Ms===null){Ie===null&&(Ie=xt);break}n&&Ie&&Ms.alternate===null&&r(W,Ie),P=g(Ms,P,at),kt===null?We=Ms:kt.sibling=Ms,kt=Ms,Ie=xt}if(Et.done)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;!Et.done;at++,Et=Q.next())Et=fe(W,Et.value,de),Et!==null&&(P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return bt&&Ur(W,at),We}for(Ie=u(Ie);!Et.done;at++,Et=Q.next())Et=le(Ie,W,at,Et.value,de),Et!==null&&(n&&Et.alternate!==null&&Ie.delete(Et.key===null?at:Et.key),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return n&&Ie.forEach(function(fC){return r(W,fC)}),bt&&Ur(W,at),We}function Pt(W,P,Q,de){if(typeof Q=="object"&&Q!==null&&Q.type===N&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case v:e:{for(var We=Q.key;P!==null;){if(P.key===We){if(We=Q.type,We===N){if(P.tag===7){l(W,P.sibling),de=m(P,Q.props.children),de.return=W,W=de;break e}}else if(P.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===ue&&ia(We)===P.type){l(W,P.sibling),de=m(P,Q.props),Ol(de,Q),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Q.type===N?(de=Zs(Q.props.children,W.mode,de,Q.key),de.return=W,W=de):(de=rc(Q.type,Q.key,Q.props,null,W.mode,de),Ol(de,Q),de.return=W,W=de)}return y(W);case S:e:{for(We=Q.key;P!==null;){if(P.key===We)if(P.tag===4&&P.stateNode.containerInfo===Q.containerInfo&&P.stateNode.implementation===Q.implementation){l(W,P.sibling),de=m(P,Q.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Q,W.mode,de),de.return=W,W=de}return y(W);case ue:return Q=ia(Q),Pt(W,P,Q,de)}if(H(Q))return Le(W,P,Q,de);if($(Q)){if(We=$(Q),typeof We!="function")throw Error(s(150));return Q=We.call(Q),Ve(W,P,Q,de)}if(typeof Q.then=="function")return Pt(W,P,hc(Q),de);if(Q.$$typeof===I)return Pt(W,P,lc(W,Q),de);dc(W,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Q),de.return=W,W=de):(l(W,P),de=hh(Q,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Q,de){try{Ll=0;var We=Pt(W,P,Q,de);return Pa=null,We}catch(Ie){if(Ie===za||Ie===cc)throw Ie;var kt=Pn(29,Ie,null,W.mode);return kt.lanes=de,kt.return=W,kt}finally{}}}var ra=gg(!0),xg=gg(!1),gs=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(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 xs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function _s(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function zl(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,Mn(n,l)}}function Eh(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 y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,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 Nh=!1;function Pl(){if(Nh){var n=Oa;if(n!==null)throw n}}function Il(n,r,l,u){Nh=!1;var m=n.updateQueue;gs=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var O=k,J=O.next;O.next=null,y===null?g=J:y.next=J,y=O;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==y&&(k===null?ce.firstBaseUpdate=J:k.next=J,ce.lastBaseUpdate=O))}if(g!==null){var fe=m.baseState;y=0,ce=J=O=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(gt&ie)===ie:(u&ie)===ie){ie!==0&&ie===La&&(Nh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Le=n,Ve=k;ie=r;var Pt=l;switch(Ve.tag){case 1:if(Le=Ve.payload,typeof Le=="function"){fe=Le.call(Pt,fe,ie);break e}fe=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ve.payload,ie=typeof Le=="function"?Le.call(Pt,fe,ie):Le,ie==null)break e;fe=x({},fe,ie);break e;case 2:gs=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(J=ce=le,O=fe):ce=ce.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ce===null&&(O=fe),m.baseState=O,m.firstBaseUpdate=J,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),ws|=y,n.lanes=y,n.memoizedState=fe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var O=m(),J=T.S;if(J!==null&&J(k,O),O!==null&&typeof O=="object"&&typeof O.then=="function"){var ce=iw(O,u);$l(n,r,ce,Fn(n))}else $l(n,r,u,Fn(n))}catch(fe){$l(n,r,{then:function(){},status:"rejected",reason:fe},Fn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,F,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:F},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),$l(n,r.next.queue,{},Fn())}function Wh(){return Ji(so)}function Jg(){return _i().memoizedState}function ex(){return _i().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Fn();n=xs(l);var u=_s(r,n,l);u!==null&&(jn(u,r,l),zl(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Fn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(jn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Fn();$l(n,r,l,u)}function $l(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,zn(k,y))return ic(n,r,m,0),Ft===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return jn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&jn(r,n,2)}function Sc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function ix(n,r){Ha=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Mn(n,l)}}var Fl={readContext:Ji,use:_c,useCallback:ci,useContext:ci,useEffect:ci,useImperativeHandle:ci,useLayoutEffect:ci,useInsertionEffect:ci,useMemo:ci,useReducer:ci,useRef:ci,useState:ci,useDebugValue:ci,useDeferredValue:ci,useTransition:ci,useSyncExternalStore:ci,useId:ci,useHostTransitionStatus:ci,useFormState:ci,useActionState:ci,useOptimistic:ci,useMemoCache:ci,useCacheRefresh:ci};Fl.useEffectEvent=ci;var rx={readContext:Ji,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Yt(!0);try{n()}finally{Yt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Yt(!0);try{l(r)}finally{Yt(!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=uw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,rt,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(gt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,$a(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=Ft.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-ot(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Zt]=r,g[te]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(tn(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&&Yr(r)}}return ei(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Yr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ma(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Zt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||ps(r,!0)}else n=$c(n).createTextNode(u),n[Zt]=r,r.stateNode=n}return ei(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ma(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ei(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Hn(r),r):(Hn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return ei(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ma(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[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ei(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Hn(r),r):(Hn(r),null)}return Hn(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),Nc(r,r.updateQueue),ei(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),ei(r),null;case 10:return Fr(r.type),ei(r),null;case 19:if(X(xi),u=r.memoizedState,u===null)return ei(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Wl(u,!1);else{if(ui!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,Wl(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(xi,xi.current&1|2),bt&&Ur(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Dc&&(r.flags|=128,m=!0,Wl(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),Wl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return ei(r),null}else 2*Ct()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,Wl(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=Ct(),n.sibling=null,l=xi.current,C(xi,m?l&1|2:l&1),bt&&Ur(r,u.treeForkCount),n):(ei(r),null);case 22:case 23:return Hn(r),Th(),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&&(ei(r),r.subtreeFlags&6&&(r.flags|=8192)):ei(r),l=r.updateQueue,l!==null&&Nc(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&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Fr(Ci),ei(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Fr(Ci),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return ze(r),null;case 31:if(r.memoizedState!==null){if(Hn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Hn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(xi),null;case 4:return ge(),null;case 10:return Fr(r.type),null;case 22:case 23:return Hn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Fr(Ci),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:Fr(Ci),ge();break;case 26:case 27:case 5:ze(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&Hn(r);break;case 13:Hn(r);break;case 19:X(xi);break;case 10:Fr(r.type);break;case 22:case 23:Hn(r),Th(),n!==null&&X(ta);break;case 24:Fr(Ci)}}function Gl(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,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function ys(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 y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var O=l,J=k;try{J()}catch(ce){Mt(m,O,ce)}}}u=u.next}while(u!==g)}}catch(ce){Mt(r,r.return,ce)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Yl(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){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(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){Mt(n,r,m)}else l.current=null}function Rx(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){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[te]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&js(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(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&&js(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 cd(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=dn));else if(u!==4&&(u===27&&js(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(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&&js(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);tn(r,u,l),r[Zt]=n,r[te]=l}catch(g){Mt(n,n.return,g)}}var Vr=!1,Ni=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Ui=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(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 y=0,k=-1,O=-1,J=0,ce=0,fe=n,ie=null;t:for(;;){for(var le;fe!==l||m!==0&&fe.nodeType!==3||(k=y+m),fe!==g||u!==0&&fe.nodeType!==3||(O=y+u),fe.nodeType===3&&(y+=fe.nodeValue.length),(le=fe.firstChild)!==null;)ie=fe,fe=le;for(;;){if(fe===n)break t;if(ie===l&&++J===m&&(k=y),ie===g&&++ce===u&&(O=y),(le=fe.nextSibling)!==null)break;fe=ie,ie=fe.parentNode}fe=le}l=k===-1||O===-1?null:{start:k,end:O}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,Ui=r;Ui!==null;)if(r=Ui,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Ui=n;else for(;Ui!==null;){switch(r=Ui,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"))),tn(g,u,l),g[Zt]=n,Qe(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Pt);if(W&&P&&(le.rangeCount!==1||le.anchorNode!==W.node||le.anchorOffset!==W.offset||le.focusNode!==P.node||le.focusOffset!==P.offset)){var Q=fe.createRange();Q.setStart(W.node,W.offset),le.removeAllRanges(),Ve>Pt?(le.addRange(Q),le.extend(P.node,P.offset)):(Q.setEnd(P.node,P.offset),le.addRange(Q))}}}}for(fe=[],le=k;le=le.parentNode;)le.nodeType===1&&fe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=ks,y=Jr;if(Bi=0,Ya=ks=null,Jr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Jl(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Zn(l,r),r=Xh(n.stateNode,r,2),n=_s(n,r,2),n!==null&&(Vt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(Cs===null||!Cs.has(u))){n=Zn(l,n),l=dx(2),u=_s(r,l,2),u!==null&&(fx(l,u,r,n),Vt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;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)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(gt&l)===l&&(ui===4||ui===3&&(gt&62914560)===gt&&300>Ct()-Rc?(Tt&2)===0&&Va(n,0):pd|=l,Ga===gt&&(Ga=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Vt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(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),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Xa=null,Sd=!1,Ic=!1,wd=!1,Ns=0;function Cr(n){n!==Xa&&n.next===null&&(Xa===null?Pc=Xa=n:Xa=Xa.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Jl(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-ot(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=gt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||_t(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;Ns!==0&&Iw()&&(n=Ns);for(var r=Ct(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Xa=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Bi!==0&&Bi!==5||Jl(n),Ns!==0&&(Ns=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ce=O.transferSize,fe=O.initiatorType;ce&&C_(fe)&&(O=O.responseEnd,y+=ce*(O"u"?null:document;function O_(n,r,l){var u=Za;if(u&&typeof r=="string"&&r){var m=Zi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Vw(n){es.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){es.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){es.L(n,r,l);var u=Za;if(u&&n&&r){var m='link[rel="preload"][as="'+Zi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Zi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Zi(l.imageSizes)+'"]')):m+='[href="'+Zi(n)+'"]';var g=m;switch(r){case"style":g=Qa(n);break;case"script":g=Ja(n)}nr.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),nr.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(no(g))||r==="script"&&u.querySelector(ro(g))||(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Zw(n,r){es.m(n,r);var l=Za;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Zi(u)+'"][href="'+Zi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ja(n)}if(!nr.has(g)&&(n=x({rel:"modulepreload",href:n},r),nr.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(ro(g)))return}u=l.createElement("link"),tn(u,"link",n),Qe(u),l.head.appendChild(u)}}}function Qw(n,r,l){es.S(n,r,l);var u=Za;if(u&&n){var m=Ze(u).hoistableStyles,g=Qa(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(no(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=nr.get(g))&&Id(n,l);var O=y=u.createElement("link");Qe(O),tn(O,"link",n),O._p=new Promise(function(J,ce){O.onload=J,O.onerror=ce}),O.addEventListener("load",function(){k.loading|=1}),O.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){es.X(n,r);var l=Za;if(l&&n){var u=Ze(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0},r),(r=nr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){es.M(n,r);var l=Za;if(l&&n){var u=Ze(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=nr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(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=Qa(l.href),l=Ze(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=Qa(l.href);var g=Ze(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(no(n)))&&!g._p&&(y.instance=g,y.state.loading=5),nr.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},nr.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}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=Ja(l),l=Ze(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 Qa(n){return'href="'+Zi(n)+'"'}function no(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(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}),tn(r,"link",l),Qe(r),n.head.appendChild(r))}function Ja(n){return'[src="'+Zi(n)+'"]'}function ro(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Zi(l.href)+'"]');if(u)return r.instance=u,Qe(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"),Qe(u),tn(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Qa(l.href);var g=n.querySelector(no(m));if(g)return r.state.loading|=4,r.instance=g,Qe(g),g;u=P_(l),(m=nr.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Qe(g);var y=g;return y._p=new Promise(function(k,O){y.onload=k,y.onerror=O}),tn(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Ja(l.src),(m=n.querySelector(ro(g)))?(r.instance=m,Qe(m),m):(u=l,(m=nr.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Qe(m),tn(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,qc(u,l.precedence,n));return r.instance}function qc(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,y=0;y title"):null)}function iC(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 $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(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=Qa(u.href),g=r.querySelector(no(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Qe(g);return}g=r.ownerDocument||r,u=P_(u),(m=nr.get(m))&&Id(u,m),g=g.createElement("link"),Qe(g);var y=g;y._p=new Promise(function(k,O){y.onload=k,y.onerror=O}),tn(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=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.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(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({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 f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:s}),d.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"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=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 d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.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."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.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&&d.jsx("p",{className:"text-error text-xs",children:o}),d.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 ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,L)=>fetch(E,{...L,headers:{...L==null?void 0:L.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/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(`${ef}/api/wallet/create`,{method:"POST"}),L=await E.json();if(!E.ok)throw new Error(L.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const L=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await L.json();if(!L.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(L){_(L instanceof Error?L.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.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&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.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=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.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&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(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)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.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)&&d.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 Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="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 jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[L,I]=w.useState(""),[A,q]=w.useState(!1),[R,ne]=w.useState(null),[ue,ye]=w.useState(""),[B,re]=w.useState(null),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(null),[F,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){ne("Agent name is required");return}if(!M.trim()){ne("Description is required");return}q(!0),ne(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...L.trim()&&{genre:L}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){ne(ae instanceof Error?ae.message:"Registration failed")}q(!1)},X=async()=>{if(!ue.trim()||!/^0x[a-fA-F0-9]{40}$/.test(ue)){H("Enter a valid wallet address (0x...)");return}G(!0),H(null),re(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:ue})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");re(oe)}catch(ae){H(ae instanceof Error?ae.message:"Failed to generate binding code")}G(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!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 ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.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"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:L,onChange:ae=>I(ae.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"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.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:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(F==null?void 0:F.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(F==null?void 0:F.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:F!=null&&F.codex.installed?F.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(F)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.checkedAt?new Date(F.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.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."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:ue,onChange:ae=>ye(ae.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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:$||!ue.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:$?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.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:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.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:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.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:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.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"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.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&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,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"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.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 TC="http://localhost:7777";function AC({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(`${TC}/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?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.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))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.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&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ne=new Set(R);return ne.has(q)?ne.delete(q):ne.add(q),ne})},L=q=>{var ne;const R=q.map(ue=>{var ye;return{file:ue.file,num:(ye=ue.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(ue=>ue.num!=null).sort((ue,ye)=>parseInt(ye.num)-parseInt(ue.num));return R.length>0?R[0].file:q.some(ue=>ue.file==="genesis.md")?"genesis.md":q.some(ue=>ue.file==="structure.md")?"structure.md":((ne=q[0])==null?void 0:ne.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=L(q.files);R&&s(q.name,R)}},A=q=>{const R=ne=>{if(ne==="structure.md")return 0;if(ne==="genesis.md")return 1;const ue=ne.match(/^plot-(\d+)\.md$/);return ue?2+parseInt(ue[1]):100};return[...q].sort((ne,ue)=>R(ne.file)-R(ue.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.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:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:A(q.files).map(R=>{const ne=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ne?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.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:d.jsx("span",{children:"Archives"})})})]})}/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -57,21 +57,21 @@ Error generating stack: `+u.message+` * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},fi=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Hs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",$s=" ",Uo=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 zy;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}},Nu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},ar=class Iy extends Uo{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Hs(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()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Ki(e){if(tf.has(e))return tf.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");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Ki("BufferService"),Hy=Ki("CoreMouseService"),va=Ki("CoreService"),qC=Ki("CharsetService"),qp=Ki("InstantiationService"),Uy=Ki("LogService"),bn=Ki("OptionsService"),$y=Ki("OscLinkService"),WC=Ki("UnicodeService"),$o=Ki("DecorationService"),qf=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 ar,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=fi([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},fi=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(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&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(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 pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Ps(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(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 HC=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}},UC=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,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===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=f;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}},Oy="",Hs=" ",$o=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}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 zy;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}},Nu=class Py{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 Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},or=class Iy extends $o{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;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?Ps(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()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Xi(e){if(tf.has(e))return tf.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");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Xi("BufferService"),Hy=Xi("CoreMouseService"),va=Xi("CoreService"),qC=Xi("CharsetService"),qp=Xi("InstantiationService"),Uy=Xi("LogService"),bn=Xi("OptionsService"),$y=Xi("OscLinkService"),WC=Xi("UnicodeService"),Fo=Xi("DecorationService"),qf=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 or,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=fi([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(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 Hu=Ki("CharSizeService"),as=Ki("CoreBrowserService"),Wp=Ki("MouseService"),ls=Ki("RenderService"),YC=Ki("SelectionService"),Fy=Ki("CharacterJoinerService"),fl=Ki("ThemeService"),qy=Ki("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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 Hu=Xi("CharSizeService"),as=Xi("CoreBrowserService"),Wp=Xi("MouseService"),ls=Xi("RenderService"),YC=Xi("SelectionService"),Fy=Xi("CharacterJoinerService"),gl=Xi("ThemeService"),qy=Xi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(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)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function $n(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let q=A.length-1;q>=0;q--)yield A[q]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,q){let R=0;for(let re of A)if(q(re,R++))return!0;return!1}e.some=_;function x(A,q){for(let R of A)if(q(R))return R}e.find=x;function*b(A,q){for(let R of A)q(R)&&(yield R)}e.filter=b;function*v(A,q){let R=0;for(let re of A)yield q(re,R++)}e.map=v;function*S(A,q){let R=0;for(let re of A)yield*q(re,R++)}e.flatMap=S;function*N(...A){for(let q of A)yield*q}e.concat=N;function M(A,q,R){let re=R;for(let ue of A)re=q(re,ue);return re}e.reduce=M;function*E(A,q,R=A.length){for(q<0&&(q+=A.length),R<0?R+=A.length:R>A.length&&(R=A.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 tk(...e){return si(()=>xa(e))}function si(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{xa(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var Fs=Yy,ht=class{constructor(){this._store=new Fs,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)}};ht.None=Object.freeze({dispose(){}});var ul=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}},ss=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var li=Vf,xb=class{constructor(){this._first=li.Undefined,this._last=li.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===li.Undefined}clear(){let e=this._first;for(;e!==li.Undefined;){let t=e.next;e.prev=li.Undefined,e.next=li.Undefined,e=t}this._first=li.Undefined,this._last=li.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new li(e);if(this._first===li.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!==li.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==li.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==li.Undefined&&e.next!==li.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===li.Undefined&&e.next===li.Undefined?(this._first=li.Undefined,this._last=li.Undefined):e.next===li.Undefined?(this._last=this._last.prev,this._last.next=li.Undefined):e.prev===li.Undefined&&(this._first=this._first.next,this._first.prev=li.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==li.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},sn;(e=>{e.None=()=>ht.None;function t($,G){return x($,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i($){return(G,V=null,H)=>{let T=!1,z;return z=$(F=>{if(!T)return z?z.dispose():T=!0,G.call(V,F)},null,H),T&&z.dispose(),z}}e.once=i;function s($,G,V){return f((H,T=null,z)=>$(F=>H.call(T,G(F)),null,z),V)}e.map=s;function a($,G,V){return f((H,T=null,z)=>$(F=>{G(F),H.call(T,F)},null,z),V)}e.forEach=a;function o($,G,V){return f((H,T=null,z)=>$(F=>G(F)&&H.call(T,F),null,z),V)}e.filter=o;function c($){return $}e.signal=c;function h(...$){return(G,V=null,H)=>{let T=tk(...$.map(z=>z(F=>G.call(V,F))));return _(T,H)}}e.any=h;function p($,G,V,H){let T=V;return s($,z=>(T=G(T,z),T),H)}e.reduce=p;function f($,G){let V,H={onWillAddFirstListener(){V=$(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new ke(H);return G==null||G.add(T),T.event}function _($,G){return G instanceof Array?G.push($):G&&G.add($),$}function x($,G,V=100,H=!1,T=!1,z,F){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=$(oe=>{X++,j=G(j,oe),H&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!H||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new ke(Z);return F==null||F.add(ae),ae.event}e.debounce=x;function b($,G=0,V){return e.debounce($,(H,T)=>H?(H.push(T),H):[T],G,void 0,!0,void 0,V)}e.accumulate=b;function v($,G=(H,T)=>H===T,V){let H=!0,T;return o($,z=>{let F=H||!G(z,T);return H=!1,T=z,F},V)}e.latch=v;function S($,G,V){return[e.filter($,G,V),e.filter($,H=>!G(H),V)]}e.split=S;function N($,G=!1,V=[],H){let T=V.slice(),z=$(j=>{T?T.push(j):xe.fire(j)});H&&H.add(z);let F=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new ke({onWillAddFirstListener(){z||(z=$(j=>xe.fire(j)),H&&H.add(z))},onDidAddFirstListener(){T&&(G?setTimeout(F):F())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return H&&H.add(xe),xe.event}e.buffer=N;function M($,G){return(V,H,T)=>{let z=G(new O);return $(function(F){let xe=z.evaluate(F);xe!==E&&V.call(H,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(V=>(G(V),V)),this}filter(G){return this.steps.push(V=>G(V)?V:E),this}reduce(G,V){let H=V;return this.steps.push(T=>(H=G(H,T),H)),this}latch(G=(V,H)=>V===H){let V=!0,H;return this.steps.push(T=>{let z=V||!G(T,H);return V=!1,H=T,z?T:E}),this}evaluate(G){for(let V of this.steps)if(G=V(G),G===E)break;return G}}function I($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.on(G,H),z=()=>$.removeListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromNodeEventEmitter=I;function A($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.addEventListener(G,H),z=()=>$.removeEventListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromDOMEventEmitter=A;function q($){return new Promise(G=>i($)(G))}e.toPromise=q;function R($){let G=new ke;return $.then(V=>{G.fire(V)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function re($,G){return $(V=>G.fire(V))}e.forward=re;function ue($,G,V){return G(V),$(H=>G(H))}e.runAndSubscribe=ue;class ye{constructor(G,V){this._observable=G,this._counter=0,this._hasChanged=!1;let H={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(H),V&&V.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,V){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 B($,G){return new ye($,G).emitter.event}e.fromObservable=B;function se($){return(G,V,H)=>{let T=0,z=!1,F={beginUpdate(){T++},endUpdate(){T--,T===0&&($.reportChanges(),z&&(z=!1,G.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};$.addObserver(F),$.reportChanges();let xe={dispose(){$.removeObserver(F)}};return H instanceof Fs?H.add(xe):Array.isArray(H)&&H.push(xe),xe}}e.fromObservableLight=se})(sn||(sn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function qn(e,t=0){return e[e.length-(1+t)]}var JC;(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})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let q=A.length-1;q>=0;q--)yield A[q]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,q){let R=0;for(let ne of A)if(q(ne,R++))return!0;return!1}e.some=_;function x(A,q){for(let R of A)if(q(R))return R}e.find=x;function*b(A,q){for(let R of A)q(R)&&(yield R)}e.filter=b;function*v(A,q){let R=0;for(let ne of A)yield q(ne,R++)}e.map=v;function*S(A,q){let R=0;for(let ne of A)yield*q(ne,R++)}e.flatMap=S;function*N(...A){for(let q of A)yield*q}e.concat=N;function M(A,q,R){let ne=R;for(let ue of A)ne=q(ne,ue);return ne}e.reduce=M;function*E(A,q,R=A.length){for(q<0&&(q+=A.length),R<0?R+=A.length:R>A.length&&(R=A.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 tk(...e){return ni(()=>xa(e))}function ni(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{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{xa(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?Vy.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)}};Yy.DISABLE_DISPOSED_WARNING=!1;var Us=Yy,ht=class{constructor(){this._store=new Us,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)}};ht.None=Object.freeze({dispose(){}});var fl=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}},ss=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var si=Vf,xb=class{constructor(){this._first=si.Undefined,this._last=si.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===si.Undefined}clear(){let e=this._first;for(;e!==si.Undefined;){let t=e.next;e.prev=si.Undefined,e.next=si.Undefined,e=t}this._first=si.Undefined,this._last=si.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new si(e);if(this._first===si.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!==si.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==si.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==si.Undefined&&e.next!==si.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===si.Undefined&&e.next===si.Undefined?(this._first=si.Undefined,this._last=si.Undefined):e.next===si.Undefined?(this._last=this._last.prev,this._last.next=si.Undefined):e.prev===si.Undefined&&(this._first=this._first.next,this._first.prev=si.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==si.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&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}},sn;(e=>{e.None=()=>ht.None;function t($,G){return x($,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i($){return(G,V=null,H)=>{let T=!1,z;return z=$(F=>{if(!T)return z?z.dispose():T=!0,G.call(V,F)},null,H),T&&z.dispose(),z}}e.once=i;function s($,G,V){return f((H,T=null,z)=>$(F=>H.call(T,G(F)),null,z),V)}e.map=s;function a($,G,V){return f((H,T=null,z)=>$(F=>{G(F),H.call(T,F)},null,z),V)}e.forEach=a;function o($,G,V){return f((H,T=null,z)=>$(F=>G(F)&&H.call(T,F),null,z),V)}e.filter=o;function c($){return $}e.signal=c;function h(...$){return(G,V=null,H)=>{let T=tk(...$.map(z=>z(F=>G.call(V,F))));return _(T,H)}}e.any=h;function p($,G,V,H){let T=V;return s($,z=>(T=G(T,z),T),H)}e.reduce=p;function f($,G){let V,H={onWillAddFirstListener(){V=$(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new ke(H);return G==null||G.add(T),T.event}function _($,G){return G instanceof Array?G.push($):G&&G.add($),$}function x($,G,V=100,H=!1,T=!1,z,F){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=$(oe=>{X++,j=G(j,oe),H&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!H||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new ke(Z);return F==null||F.add(ae),ae.event}e.debounce=x;function b($,G=0,V){return e.debounce($,(H,T)=>H?(H.push(T),H):[T],G,void 0,!0,void 0,V)}e.accumulate=b;function v($,G=(H,T)=>H===T,V){let H=!0,T;return o($,z=>{let F=H||!G(z,T);return H=!1,T=z,F},V)}e.latch=v;function S($,G,V){return[e.filter($,G,V),e.filter($,H=>!G(H),V)]}e.split=S;function N($,G=!1,V=[],H){let T=V.slice(),z=$(j=>{T?T.push(j):xe.fire(j)});H&&H.add(z);let F=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new ke({onWillAddFirstListener(){z||(z=$(j=>xe.fire(j)),H&&H.add(z))},onDidAddFirstListener(){T&&(G?setTimeout(F):F())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return H&&H.add(xe),xe.event}e.buffer=N;function M($,G){return(V,H,T)=>{let z=G(new L);return $(function(F){let xe=z.evaluate(F);xe!==E&&V.call(H,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class L{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(V=>(G(V),V)),this}filter(G){return this.steps.push(V=>G(V)?V:E),this}reduce(G,V){let H=V;return this.steps.push(T=>(H=G(H,T),H)),this}latch(G=(V,H)=>V===H){let V=!0,H;return this.steps.push(T=>{let z=V||!G(T,H);return V=!1,H=T,z?T:E}),this}evaluate(G){for(let V of this.steps)if(G=V(G),G===E)break;return G}}function I($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.on(G,H),z=()=>$.removeListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromNodeEventEmitter=I;function A($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.addEventListener(G,H),z=()=>$.removeEventListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromDOMEventEmitter=A;function q($){return new Promise(G=>i($)(G))}e.toPromise=q;function R($){let G=new ke;return $.then(V=>{G.fire(V)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ne($,G){return $(V=>G.fire(V))}e.forward=ne;function ue($,G,V){return G(V),$(H=>G(H))}e.runAndSubscribe=ue;class ye{constructor(G,V){this._observable=G,this._counter=0,this._hasChanged=!1;let H={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(H),V&&V.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,V){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 B($,G){return new ye($,G).emitter.event}e.fromObservable=B;function re($){return(G,V,H)=>{let T=0,z=!1,F={beginUpdate(){T++},endUpdate(){T--,T===0&&($.reportChanges(),z&&(z=!1,G.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};$.addObserver(F),$.reportChanges();let xe={dispose(){$.removeObserver(F)}};return H instanceof Us?H.add(xe):Array.isArray(H)&&H.push(xe),xe}}e.fromObservableLight=re})(sn||(sn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,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}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=si(()=>{o==null||o(),this._removeListener(a)});return s instanceof Fs?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Qf=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}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var pl=typeof navigator=="object"?navigator.userAgent:"",Jf=pl.indexOf("Firefox")>=0,gk=pl.indexOf("AppleWebKit")>=0,Yp=pl.indexOf("Chrome")>=0,xk=!Yp&&pl.indexOf("Safari")>=0;pl.indexOf("Electron/")>=0;pl.indexOf("Android")>=0;var rf=!1;if(typeof ss.matchMedia=="function"){let e=ss.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ss.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(ss,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var sl="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=sl,_b=sl,_k,fr,ga=globalThis,rn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?rn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(rn=process);var Ay,bk=typeof((Ay=rn==null?void 0:rn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(rn==null?void 0:rn.type)==="renderer",Ry;if(typeof rn=="object"){ep=rn.platform==="win32",tp=rn.platform==="darwin",xu=rn.platform==="linux",xu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=sl,_u=sl;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||sl,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(fr=navigator.userAgent,ep=fr.indexOf("Windows")>=0,tp=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||sl,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=fr,Os=_u,Sk;(e=>{function t(){return Os}e.value=t;function i(){return Os.length===2?Os==="en":Os.length>=3?Os[0]==="e"&&Os[1]==="n"&&Os[2]==="-":!1}e.isDefaultVariant=i;function s(){return Os==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.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}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var Qa=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Qa&&Qa.clipboard&&Qa.clipboard.writeText,bb||Qa&&Qa.clipboard&&Qa.clipboard.readText;var Vp=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}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:sn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=si(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=class nr{static fromArray(t){return new nr(i=>{i.emitMany(t)})}static fromPromise(t){return new nr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new nr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new nr(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 nr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return nr.map(this,t)}static filter(t,i){return new nr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return nr.filter(this,t)}static coalesce(t){return nr.filter(t,i=>!!i)}coalesce(){return nr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return nr.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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:ss,disposables:new Fs};e.set(ss.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 ht.None;let h=new Fs,p={window:c,disposables:h.add(new Fs)};return e.set(c.vscodeWindowId,p),h.add(si(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ke(c,Ui.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:ss},getDocument(c){return Tr(c).document}}})(),Uk=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 Ke(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ke(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){gu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Ui={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"},qk=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=En(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=En(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=En(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=En(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=En(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=En(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=En(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=En(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=En(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=En(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=En(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=En(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=En(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=En(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 En(e){return typeof e=="number"?`${e}px`:e}function To(e){return new qk(e)}var r0=class{constructor(){this._hooks=new Fs,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(si(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ke(o,Ui.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ke(o,Ui.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var So=class on extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ke(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ke(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ke(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:ss,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return si(i)}static ignoreTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return si(i)}static isTouchDevice(){return"ontouchstart"in ss||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=on.HOLD_DELAY&&Math.abs(p.initialPageX-$n(p.rollingPageX))<30&&Math.abs(p.initialPageY-$n(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=$n(p.rollingPageX),_.pageY=$n(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=$n(p.rollingPageX),x=$n(p.rollingPageY),b=$n(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>on.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};So.SCROLL_FRICTION=-.005,So.HOLD_DELAY=700,So.CLEAR_TAP_COUNT_TIME=400,fi([Wk],So,"isTouchDevice",1);var Gk=So,Zp=class extends ht{onclick(e,t){this._register(Ke(e,Ui.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ke(e,Ui.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ke(e,Ui.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ke(e,Ui.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ke(e,Ui.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ke(e,Ui.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ke(e,Ui.INPUT,t))}onblur(e,t){this._register(Ke(e,Ui.BLUR,t))}onfocus(e,t){this._register(Ke(e,Ui.FOCUS,t))}onchange(e,t){this._register(Ke(e,Ui.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Vk=class ip{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 ip(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 ip(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}}},Kk=class extends ht{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 Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Zp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=To(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(Ke(this.domNode.domNode,Ui.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=To(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(Ke(this.slider.domNode,Ui.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=Fk(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(e0&&c>e2){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()}},a0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{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=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=To(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=To(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=To(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 Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(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,Rr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ke(this._listenOnDomNode,Ui.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Rr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Rr&&(t.className+=" mac"),t}var ap=class extends ht{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 Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(si(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(si(()=>this._styleElement.remove())),this._register(sn.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(f=>this._handleScroll(f)))}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}};ap=fi([Re(2,_n),Re(3,as),Re(4,Hy),Re(5,fl),Re(6,bn),Re(7,ls)],ap);var lp=class extends ht{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(si(()=>{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()}};lp=fi([Re(1,_n),Re(2,as),Re(3,$o),Re(4,ls)],lp);var c2=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)}},kr={full:0,left:0,center:0,right:0},zs={full:0,left:0,center:0,right:0},uo={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(si(()=>{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);zs.full=this._canvas.width,zs.left=e,zs.center=t,zs.right=e,this._refreshDrawHeightConstants(),uo.full=1,uo.left=1,uo.center=1+zs.left,uo.right=1+zs.left+zs.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(uo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),zs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=fi([Re(2,_n),Re(3,$o),Re(4,ls),Re(5,bn),Re(6,fl),Re(7,as)],ju);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 bu;(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="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${pe.ESC}\\`)(l0||(l0={}));var op=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)}}};op=fi([Re(2,_n),Re(3,bn),Re(4,va),Re(5,ls)],op);var $i=0,Fi=0,qi=0,hi=0,Db={css:"#00000000",rgba:0},Ai;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(Ai||(Ai={}));var ni;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;$i=v+Math.round((_-v)*hi),Fi=S+Math.round((x-S)*hi),qi=N+Math.round((b-N)*hi);let M=Ai.toCss($i,Fi,qi),E=Ai.toRgba($i,Fi,qi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ai.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[$i,Fi,qi]=vu.toChannels(f),{css:Ai.toCss($i,Fi,qi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[$i,Fi,qi]=vu.toChannels(p.rgba),{css:Ai.toCss($i,Fi,qi,hi),rgba:Ai.toRgba($i,Fi,qi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ni||(ni={}));var oi;(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 $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),Ai.toColor($i,Fi,qi);case 5:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),Ai.toColor($i,Fi,qi,hi);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 $i=parseInt(o[1]),Fi=parseInt(o[2]),qi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ai.toColor($i,Fi,qi,hi);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),[$i,Fi,qi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ai.toRgba($i,Fi,qi,hi),css:a}}e.toColor=s})(oi||(oi={}));var pn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return $i=x+Math.round((p-x)*hi),Fi=b+Math.round((f-b)*hi),qi=v+Math.round((_-v)*hi),Ai.toRgba($i,Fi,qi)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,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})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||$s.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,F=this._workCell;if(b.length>0&&G===b[0][0]&&T){let we=b.shift(),He=this._isCellInSelection(we[0],t);for(O=we[0]+1;O=we[1]),T?(H=!0,F=new u2(this._workCell,e.translateToString(!0,we[0],we[1]),we[1]-we[0]),z=we[1]-1,V=F.getWidth()):B=we[1]}let xe=this._isCellInSelection(G,t),j=i&&G===o,D=$&&G>=f&&G<=_,X=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{X=!0});let C=F.getChars()||$s;if(C===" "&&(F.isUnderline()||F.isOverline())&&(C=" "),ye=V*h-p.get(C,F.isBold(),F.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&ue||!xe&&!ue&&F.bg===I)&&(xe&&ue&&v.selectionForeground||F.fg===A)&&F.extended.ext===q&&D===R&&ye===re&&!j&&!H&&!X&&T){F.isInvisible()?E+=$s:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=F.bg,A=F.fg,q=F.extended.ext,R=D,re=ye,ue=xe,H&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&j&&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(F.isBold()&&se.push("xterm-bold"),F.isItalic()&&se.push("xterm-italic"),F.isDim()&&se.push("xterm-dim"),F.isInvisible()?E=$s:E=F.getChars()||$s,F.isUnderline()&&(se.push(`xterm-underline-${F.extended.underlineStyle}`),E===" "&&(E=" "),!F.isUnderlineColorDefault()))if(F.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Uo.toColorRGB(F.getUnderlineColor()).join(",")})`;else{let we=F.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&F.isBold()&&we<8&&(we+=8),N.style.textDecorationColor=v.ansi[we].css}F.isOverline()&&(se.push("xterm-overline"),E===" "&&(E=" ")),F.isStrikethrough()&&se.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=F.getFgColor(),ae=F.getFgColorMode(),oe=F.getBgColor(),K=F.getBgColorMode(),he=!!F.isInverse();if(he){let we=Z;Z=oe,oe=we;let He=ae;ae=K,K=He}let ge,De,ze=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{we.options.layer!=="top"&&ze||(we.backgroundColorRGB&&(K=50331648,oe=we.backgroundColorRGB.rgba>>8&16777215,ge=we.backgroundColorRGB),we.foregroundColorRGB&&(ae=50331648,Z=we.foregroundColorRGB.rgba>>8&16777215,De=we.foregroundColorRGB),ze=we.options.layer==="top")}),!ze&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,ze=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),ze&&se.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],se.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ai.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:he?(Fe=v.foreground,se.push("xterm-bg-257")):Fe=v.background}switch(ge||F.isDim()&&(ge=ni.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:F.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],F,ge,void 0)||se.push(`xterm-fg-${Z}`);break;case 50331648:let we=Ai.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,we,F,ge,De)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,F,ge,De)||he&&se.push("xterm-fg-257")}se.length&&(N.className=se.join(" "),se.length=0),!j&&!H&&!X&&T?M++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=ni.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]}};cp=fi([Re(1,Fy),Re(2,bn),Re(3,as),Re(4,va),Re(5,$o),Re(6,fl)],cp);function Mb(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}},g2=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 x2(){return new g2}var lf="xterm-dom-renderer-owner-",ir="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",ho="xterm-focus",au="xterm-selection",_2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(ir),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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(si(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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} .${ir} 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} .${ir} { 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} .${ir} .xterm-dim { color: ${ni.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} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ho} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ir} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ni.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ni.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ni.multiplyOpacity(ni.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(ho),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ho),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=fi([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,as),Re(13,fl)],up);var hp=class extends ht{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 v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};hp=fi([Re(2,bn)],hp);var o0=class extends ht{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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=class extends ht{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 S2(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(sn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ke(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ke(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}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ul),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(si(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ke(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)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(si(()=>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 Qp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Qp(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])}}};dp=fi([Re(0,ls),Re(1,Hu)],dp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,Fo=Uu?"node":navigator.userAgent,qo=Uu?"node":navigator.platform,u0=Fo.includes("Firefox"),E2=Fo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(Fo);function N2(){if(!h0)return 0;let e=Fo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(qo),j2=qo==="iPad",T2=qo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(qo),Jp=qo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(Fo),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{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 ul),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new ul),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 k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(si(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=si(()=>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()}};fp=fi([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,$o),Re(6,_n),Re(7,as),Re(8,fl)],fp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Lo(Math.abs(a-e),Bo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Lo(p,Bo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Lo(g0(e,t,e,t-_a(t,a),!1,a).length,Bo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Lo(c,Bo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Lo(g0(e,c,i,h,p==="C",a).length,Bo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Bo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Lo(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 Lb(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 of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=class extends ht{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 ar,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=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(si(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r +`))}},ok=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},ck=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},uk=0,nf=class{constructor(e){this.value=e,this.id=uk++}},hk=2,dk,ke=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new ak((t==null?void 0:t.onListenerError)??gu,((s=this._options)==null?void 0:s.leakWarningThreshold)??sk):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new rk(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,f,_,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],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ni(()=>{o==null||o(),this._removeListener(a)});return s instanceof Us?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*hk<=i.length){let f=0;for(let _=0;_0}},fk=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}},Qf=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}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var xl=typeof navigator=="object"?navigator.userAgent:"",Jf=xl.indexOf("Firefox")>=0,gk=xl.indexOf("AppleWebKit")>=0,Yp=xl.indexOf("Chrome")>=0,xk=!Yp&&xl.indexOf("Safari")>=0;xl.indexOf("Electron/")>=0;xl.indexOf("Android")>=0;var rf=!1;if(typeof ss.matchMedia=="function"){let e=ss.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ss.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(ss,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var ol="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=ol,_b=ol,_k,gr,ga=globalThis,rn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?rn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(rn=process);var Ay,bk=typeof((Ay=rn==null?void 0:rn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(rn==null?void 0:rn.type)==="renderer",Ry;if(typeof rn=="object"){ep=rn.platform==="win32",tp=rn.platform==="darwin",xu=rn.platform==="linux",xu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=ol,_u=ol;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||ol,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(gr=navigator.userAgent,ep=gr.indexOf("Windows")>=0,tp=gr.indexOf("Macintosh")>=0,(gr.indexOf("Macintosh")>=0||gr.indexOf("iPad")>=0||gr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=gr.indexOf("Linux")>=0,(gr==null?void 0:gr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||ol,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=gr,Bs=_u,Sk;(e=>{function t(){return Bs}e.value=t;function i(){return Bs.length===2?Bs==="en":Bs.length>=3?Bs[0]==="e"&&Bs[1]==="n"&&Bs[2]==="-":!1}e.isDefaultVariant=i;function s(){return Bs==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.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}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var tl=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||tl&&tl.clipboard&&tl.clipboard.writeText,bb||tl&&tl.clipboard&&tl.clipboard.readText;var Vp=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}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.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 sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{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 i0&&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 Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("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 Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:sn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=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?n0:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=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 Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=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 Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ni(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(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})(Pk||(Pk={}));var kb=class sr{static fromArray(t){return new sr(i=>{i.emitMany(t)})}static fromPromise(t){return new sr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new sr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new sr(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 sr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return sr.map(this,t)}static filter(t,i){return new sr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return sr.filter(this,t)}static coalesce(t){return sr.filter(t,i=>!!i)}coalesce(){return sr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return sr.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())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:ss,disposables:new Us};e.set(ss.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 ht.None;let h=new Us,p={window:c,disposables:h.add(new Us)};return e.set(c.vscodeWindowId,p),h.add(ni(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ke(c,$i.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 f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:ss},getDocument(c){return Tr(c).document}}})(),Uk=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 Ke(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ke(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=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){gu(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(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var $i={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"},qk=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=Tn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Tn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Tn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Tn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Tn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Tn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Tn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Tn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Tn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Tn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Tn(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=Tn(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=Tn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Tn(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 Tn(e){return typeof e=="number"?`${e}px`:e}function Ao(e){return new qk(e)}var r0=class{constructor(){this._hooks=new Us,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(ni(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ke(o,$i.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ke(o,$i.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(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 Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var wo=class on extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ke(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ke(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ke(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:ss,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return ni(i)}static ignoreTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return ni(i)}static isTouchDevice(){return"ontouchstart"in ss||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=on.HOLD_DELAY&&Math.abs(p.initialPageX-qn(p.rollingPageX))<30&&Math.abs(p.initialPageY-qn(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=qn(p.rollingPageX),_.pageY=qn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=qn(p.rollingPageX),x=qn(p.rollingPageY),b=qn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.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===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>on.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.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,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+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)}};wo.SCROLL_FRICTION=-.005,wo.HOLD_DELAY=700,wo.CLEAR_TAP_COUNT_TIME=400,fi([Wk],wo,"isTouchDevice",1);var Gk=wo,Zp=class extends ht{onclick(e,t){this._register(Ke(e,$i.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ke(e,$i.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ke(e,$i.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ke(e,$i.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ke(e,$i.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ke(e,$i.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ke(e,$i.INPUT,t))}onblur(e,t){this._register(Ke(e,$i.BLUR,t))}onfocus(e,t){this._register(Ke(e,$i.FOCUS,t))}onchange(e,t){this._register(Ke(e,$i.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{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=jb+"px",this.domNode.style.height=jb+"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 r0),this._register(Eb(this.bgDomNode,$i.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,$i.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(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()}},Vk=class ip{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 ip(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 ip(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}}},Kk=class extends ht{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 Vk(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 Ab(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=Ab.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)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(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":"")))}},e2=140,s0=class extends Zp{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 Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=Ao(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(Ke(this.domNode.domNode,$i.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Ao(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(Ke(this.slider.domNode,$i.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=Fk(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(e0&&c>e2){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()}},a0=class rp{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 rp(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 f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._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),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{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=o2(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 i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(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=Ao(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ao(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ao(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 Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(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,Rr&&(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 Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ke(this._listenOnDomNode,$i.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.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=!Rr&&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(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),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(),n2)}},l2=class extends a2{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 o2(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,Rr&&(t.className+=" mac"),t}var ap=class extends ht{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 Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(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(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ni(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ni(()=>this._styleElement.remove())),this._register(sn.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(f=>this._handleScroll(f)))}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}};ap=fi([Re(2,_n),Re(3,as),Re(4,Hy),Re(5,gl),Re(6,bn),Re(7,ls)],ap);var lp=class extends ht{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(ni(()=>{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()}};lp=fi([Re(1,_n),Re(2,as),Re(3,Fo),Re(4,ls)],lp);var c2=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)}},kr={full:0,left:0,center:0,right:0},Ls={full:0,left:0,center:0,right:0},ho={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;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 c2,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(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ni(()=>{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);Ls.full=this._canvas.width,Ls.left=e,Ls.center=t,Ls.right=e,this._refreshDrawHeightConstants(),ho.full=1,ho.left=1,ho.center=1+Ls.left,ho.right=1+Ls.left+Ls.center}_refreshDrawHeightConstants(){kr.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);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.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(ho[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Ls[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[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}))}};ju=fi([Re(2,_n),Re(3,Fo),Re(4,ls),Re(5,bn),Re(6,gl),Re(7,as)],ju);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 bu;(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="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${pe.ESC}\\`)(l0||(l0={}));var op=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)}}};op=fi([Re(2,_n),Re(3,bn),Re(4,va),Re(5,ls)],op);var Fi=0,qi=0,Wi=0,hi=0,Db={css:"#00000000",rgba:0},Ai;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(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})(Ai||(Ai={}));var ti;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Fi=v+Math.round((_-v)*hi),qi=S+Math.round((x-S)*hi),Wi=N+Math.round((b-N)*hi);let M=Ai.toCss(Fi,qi,Wi),E=Ai.toRgba(Fi,qi,Wi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ai.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Fi,qi,Wi]=vu.toChannels(f),{css:Ai.toCss(Fi,qi,Wi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[Fi,qi,Wi]=vu.toChannels(p.rgba),{css:Ai.toCss(Fi,qi,Wi,hi),rgba:Ai.toRgba(Fi,qi,Wi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ti||(ti={}));var ai;(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 Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),Ai.toColor(Fi,qi,Wi);case 5:return Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),Ai.toColor(Fi,qi,Wi,hi);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 Fi=parseInt(o[1]),qi=parseInt(o[2]),Wi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ai.toColor(Fi,qi,Wi,hi);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),[Fi,qi,Wi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ai.toRgba(Fi,qi,Wi,hi),css:a}}e.toColor=s})(ai||(ai={}));var pn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Fi=x+Math.round((p-x)*hi),qi=b+Math.round((f-b)*hi),Wi=v+Math.round((_-v)*hi),Ai.toRgba(Fi,qi,Wi)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,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})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Hs.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,F=this._workCell;if(b.length>0&&G===b[0][0]&&T){let we=b.shift(),He=this._isCellInSelection(we[0],t);for(L=we[0]+1;L=we[1]),T?(H=!0,F=new u2(this._workCell,e.translateToString(!0,we[0],we[1]),we[1]-we[0]),z=we[1]-1,V=F.getWidth()):B=we[1]}let xe=this._isCellInSelection(G,t),j=i&&G===o,D=$&&G>=f&&G<=_,X=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{X=!0});let C=F.getChars()||Hs;if(C===" "&&(F.isUnderline()||F.isOverline())&&(C=" "),ye=V*h-p.get(C,F.isBold(),F.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&ue||!xe&&!ue&&F.bg===I)&&(xe&&ue&&v.selectionForeground||F.fg===A)&&F.extended.ext===q&&D===R&&ye===ne&&!j&&!H&&!X&&T){F.isInvisible()?E+=Hs:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=F.bg,A=F.fg,q=F.extended.ext,R=D,ne=ye,ue=xe,H&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&j&&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(F.isBold()&&re.push("xterm-bold"),F.isItalic()&&re.push("xterm-italic"),F.isDim()&&re.push("xterm-dim"),F.isInvisible()?E=Hs:E=F.getChars()||Hs,F.isUnderline()&&(re.push(`xterm-underline-${F.extended.underlineStyle}`),E===" "&&(E=" "),!F.isUnderlineColorDefault()))if(F.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${$o.toColorRGB(F.getUnderlineColor()).join(",")})`;else{let we=F.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&F.isBold()&&we<8&&(we+=8),N.style.textDecorationColor=v.ansi[we].css}F.isOverline()&&(re.push("xterm-overline"),E===" "&&(E=" ")),F.isStrikethrough()&&re.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=F.getFgColor(),ae=F.getFgColorMode(),oe=F.getBgColor(),K=F.getBgColorMode(),he=!!F.isInverse();if(he){let we=Z;Z=oe,oe=we;let He=ae;ae=K,K=He}let ge,De,ze=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{we.options.layer!=="top"&&ze||(we.backgroundColorRGB&&(K=50331648,oe=we.backgroundColorRGB.rgba>>8&16777215,ge=we.backgroundColorRGB),we.foregroundColorRGB&&(ae=50331648,Z=we.foregroundColorRGB.rgba>>8&16777215,De=we.foregroundColorRGB),ze=we.options.layer==="top")}),!ze&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,ze=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),ze&&re.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],re.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ai.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:he?(Fe=v.foreground,re.push("xterm-bg-257")):Fe=v.background}switch(ge||F.isDim()&&(ge=ti.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:F.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],F,ge,void 0)||re.push(`xterm-fg-${Z}`);break;case 50331648:let we=Ai.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,we,F,ge,De)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,F,ge,De)||he&&re.push("xterm-fg-257")}re.length&&(N.className=re.join(" "),re.length=0),!j&&!H&&!X&&T?M++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(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=ti.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]}};cp=fi([Re(1,Fy),Re(2,bn),Re(3,as),Re(4,va),Re(5,Fo),Re(6,gl)],cp);function Mb(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}},g2=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 x2(){return new g2}var lf="xterm-dom-renderer-owner-",rr="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",fo="xterm-focus",au="xterm-selection",_2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,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=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(rr),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(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ni(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(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} .${rr} 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} .${rr} { 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} .${rr} .xterm-dim { color: ${ti.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} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ti.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ti.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ti.multiplyOpacity(ti.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}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(fo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(fo),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,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));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 f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${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,f=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 S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=fi([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,as),Re(13,gl)],up);var hp=class extends ht{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 v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(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())}};hp=fi([Re(2,bn)],hp);var o0=class extends ht{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)}},b2=class extends o0{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}},v2=class extends o0{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}},y2=class extends ht{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 S2(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(sn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ke(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ke(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}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new fl),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(ni(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ke(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)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ni(()=>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 Qp(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 C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(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=Qp(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])}}};dp=fi([Re(0,ls),Re(1,Hu)],dp);var k2=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=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,qo=Uu?"node":navigator.userAgent,Wo=Uu?"node":navigator.platform,u0=qo.includes("Firefox"),E2=qo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(qo);function N2(){if(!h0)return 0;let e=qo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Wo),j2=Wo==="iPad",T2=Wo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(Wo),Jp=Wo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(qo),p0=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()}},A2=class extends p0{_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())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{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 fl),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new fl),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 k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ni(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.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(f=>this._registerIntersectionObserver(f,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=ni(()=>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()}};fp=fi([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,Fo),Re(6,_n),Re(7,as),Re(8,gl)],fp);var M2=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 B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Oo(Math.abs(a-e),Lo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Oo(p,Lo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Oo(g0(e,t,e,t-_a(t,a),!1,a).length,Lo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Oo(c,Lo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Oo(g0(e,c,i,h,p==="C",a).length,Lo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(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 Lo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Oo(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 Lb(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 of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=class extends ht{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 or,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=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ni(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.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(G2," ")).join(d0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&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=Lb(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=Qp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?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(),F2)}_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&&!(Au&&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,f=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+=O-1,p+=O-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let O=this._bufferService.cols-E.start;S-=O,N+=O}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};pp=fi([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,ls),Re(8,as)],pp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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()}},Bi=Object.freeze((()=>{let e=[oi.toColor("#2e3436"),oi.toColor("#cc0000"),oi.toColor("#4e9a06"),oi.toColor("#c4a000"),oi.toColor("#3465a4"),oi.toColor("#75507b"),oi.toColor("#06989a"),oi.toColor("#d3d7cf"),oi.toColor("#555753"),oi.toColor("#ef2929"),oi.toColor("#8ae234"),oi.toColor("#fce94f"),oi.toColor("#729fcf"),oi.toColor("#ad7fa8"),oi.toColor("#34e2e2"),oi.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:Ai.toCss(s,a,o),rgba:Ai.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ai.toCss(s,s,s),rgba:Ai.toRgba(s,s,s)})}return e})()),fa=oi.toColor("#ffffff"),wo=oi.toColor("#000000"),Pb=oi.toColor("#ffffff"),Ib=wo,fo={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:wo,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:fo,selectionBackgroundOpaque:ni.blend(wo,fo),selectionInactiveBackgroundTransparent:fo,selectionInactiveBackgroundOpaque:ni.blend(wo,fo),scrollbarSliderBackground:ni.opacity(fa,.2),scrollbarSliderHoverBackground:ni.opacity(fa,.4),scrollbarSliderActiveBackground:ni.opacity(fa,.5),overviewRulerBorder:fa,ansi:Bi.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=It(e.foreground,fa),t.background=It(e.background,wo),t.cursor=ni.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ni.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,fo),t.selectionBackgroundOpaque=ni.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ni.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ni.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ni.opacity(t.selectionBackgroundTransparent,.3)),ni.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ni.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ni.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ni.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ni.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Bi.slice(),t.ansi[0]=It(e.black,Bi[0]),t.ansi[1]=It(e.red,Bi[1]),t.ansi[2]=It(e.green,Bi[2]),t.ansi[3]=It(e.yellow,Bi[3]),t.ansi[4]=It(e.blue,Bi[4]),t.ansi[5]=It(e.magenta,Bi[5]),t.ansi[6]=It(e.cyan,Bi[6]),t.ansi[7]=It(e.white,Bi[7]),t.ansi[8]=It(e.brightBlack,Bi[8]),t.ansi[9]=It(e.brightRed,Bi[9]),t.ansi[10]=It(e.brightGreen,Bi[10]),t.ansi[11]=It(e.brightYellow,Bi[11]),t.ansi[12]=It(e.brightBlue,Bi[12]),t.ansi[13]=It(e.brightMagenta,Bi[13]),t.ansi[14]=It(e.brightCyan,Bi[14]),t.ansi[15]=It(e.brightWhite,Bi[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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=class extends ht{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=X2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Hs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Hs(i):a&2097151?(this._combined[t]=Hs(a&2097151)+Hs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cOo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Oo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._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(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,zi={},pa=zi.B;zi[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:"≥","{":"π","|":"≠","}":"£","~":"·"};zi.A={"#":"£"};zi.B=void 0;zi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};zi.C=zi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};zi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};zi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};zi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};zi.E=zi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};zi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};zi.H=zi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=Ti.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=ar.fromCharData([0,Oy,1,0]),this._whitespaceCell=ar.fromCharData([0,$s,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new Co(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&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ti);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 Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ti),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 Co(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ti),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ti),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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let A=Math.max(M,0);E=Oo(p,A,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends ht{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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,xp=class extends ht{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,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};xp=fi([Re(0,bn)],xp);var Ja={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...Ja};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(si(()=>{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 Ja))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Ja))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=Ja[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ja[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:Ja[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 aE(e){return e==="block"||e==="underline"||e==="bar"}function ko(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]&&ko(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{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=ko(Fb),this.decPrivateModes=ko(qb)}reset(){this.modes=ko(Fb),this.decPrivateModes=ko(qb)}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))}};_p=fi([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={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 uf(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 hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{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(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};bp=fi([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[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]],lE=[[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]],Li;function oE(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=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 po=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 vp;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>po?po: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>po?po: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,po):t}},mo=[],dE=class{constructor(){this._state=0,this._active=mo,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=mo}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=mo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||mo,!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",Iu(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=mo,this._id=-1,this._state=0}}},Fn=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+=Iu(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}},go=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=go,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}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=go,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||go,!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",Iu(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=go,this._ident=0}},Eo=new S0;Eo.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=Eo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Eo,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=Eo,this._data="",this._hitLimit=!1,i));return this._params=Eo,this._data="",this._hitLimit=!1,t}},pE=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(rr,0,2,0),e.add(rr,8,5,8),e.add(rr,6,0,6),e.add(rr,11,0,11),e.add(rr,13,13,13),e})(),gE=class extends ht{constructor(e=mE){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 S0,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(si(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ps=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ti.clone(),this._eraseAttrDataInternal=Ti.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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!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(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Fn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Fn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Fn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Fn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Fn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Fn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Fn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Fn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Fn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Fn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Fn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Fn(f=>this.restoreCursorColor(f))),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 f in zi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>Ps&&(o=this._parseStack.position+Ps)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthPs)for(let f=o;f0&&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,O=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof Co&&x.copyCellsFrom(E,O,0,M,!1);O=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Fn(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 f=1;f0||(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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Uo.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=Ti.fg,e.bg=Ti.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|=Ti.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ti.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|=Ti.fg&16777215,s.bg&=-67108864,s.bg|=Ti.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=Ti.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(!Zb(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>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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=Ti.clone(),this._eraseAttrDataInternal=Ti.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 ar;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)}},yp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=fi([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},Sp=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)))}};Sp=fi([Re(0,_n)],Sp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ul),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 K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(sn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(sn.forward(this._bufferService.onResize,this._onResize)),this._register(sn.forward(this.coreService.onData,this._onData)),this._register(sn.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(sn.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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=si(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=EE[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,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=pe.ESC+f}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 vi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(vi=this._search(t),vi===-1)||this._getKey(this._array[vi])!==t)return!1;do if(this._array[vi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vi),!0;while(++via-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&&(vi=this._search(e),!(vi<0||vi>=this._array.length)&&this._getKey(this._array[vi])===e))do yield this._array[vi];while(++vi=this._array.length)&&this._getKey(this._array[vi])===e))do t(this._array[vi]);while(++vi=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}},pf=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(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(si(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&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)}},rv=20,Du=class extends ht{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 DE(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(Ke(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(si(()=>{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===rv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;xa(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(Ke(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ke(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ke(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ke(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,xa(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}}};wp=fi([Re(1,Wp),Re(2,ls),Re(3,_n),Re(4,qy)],wp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new ul),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ul),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(TE),this._instantiationService.setService($o,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(si(()=>{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=ni.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ai.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ai.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(Du,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(Ke(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ke(this.textarea,"paste",e)),this._register(Ke(this.element,"paste",e)),u0?this._register(Ke(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ke(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ke(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ke(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ke(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ke(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ke(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ke(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ke(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ke(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(Ke(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",Uf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(as,this._coreBrowserService),this._register(Ke(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ke(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(fl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(ls,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ke(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ke(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(Ke(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.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){By(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=NE(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)&&(LE(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 ar)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=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 zE(t)}getNullCell(){return new ar}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Er=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&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=Lb(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=Qp(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,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?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(),F2)}_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&&!(Au&&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,f=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+=L-1,p+=L-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let L=this._bufferService.cols-E.start;S-=L,N+=L}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,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=Lb(i,this._bufferService.cols)}};pp=fi([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,ls),Re(8,as)],pp);var Ob=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={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}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()}},Li=Object.freeze((()=>{let e=[ai.toColor("#2e3436"),ai.toColor("#cc0000"),ai.toColor("#4e9a06"),ai.toColor("#c4a000"),ai.toColor("#3465a4"),ai.toColor("#75507b"),ai.toColor("#06989a"),ai.toColor("#d3d7cf"),ai.toColor("#555753"),ai.toColor("#ef2929"),ai.toColor("#8ae234"),ai.toColor("#fce94f"),ai.toColor("#729fcf"),ai.toColor("#ad7fa8"),ai.toColor("#34e2e2"),ai.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:Ai.toCss(s,a,o),rgba:Ai.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ai.toCss(s,s,s),rgba:Ai.toRgba(s,s,s)})}return e})()),fa=ai.toColor("#ffffff"),Co=ai.toColor("#000000"),Pb=ai.toColor("#ffffff"),Ib=Co,po={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:Co,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:po,selectionBackgroundOpaque:ti.blend(Co,po),selectionInactiveBackgroundTransparent:po,selectionInactiveBackgroundOpaque:ti.blend(Co,po),scrollbarSliderBackground:ti.opacity(fa,.2),scrollbarSliderHoverBackground:ti.opacity(fa,.4),scrollbarSliderActiveBackground:ti.opacity(fa,.5),overviewRulerBorder:fa,ansi:Li.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=It(e.foreground,fa),t.background=It(e.background,Co),t.cursor=ti.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ti.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,po),t.selectionBackgroundOpaque=ti.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ti.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ti.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ti.opacity(t.selectionBackgroundTransparent,.3)),ti.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ti.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ti.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ti.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ti.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Li.slice(),t.ansi[0]=It(e.black,Li[0]),t.ansi[1]=It(e.red,Li[1]),t.ansi[2]=It(e.green,Li[2]),t.ansi[3]=It(e.yellow,Li[3]),t.ansi[4]=It(e.blue,Li[4]),t.ansi[5]=It(e.magenta,Li[5]),t.ansi[6]=It(e.cyan,Li[6]),t.ansi[7]=It(e.white,Li[7]),t.ansi[8]=It(e.brightBlack,Li[8]),t.ansi[9]=It(e.brightRed,Li[9]),t.ansi[10]=It(e.brightGreen,Li[10]),t.ansi[11]=It(e.brightYellow,Li[11]),t.ansi[12]=It(e.brightBlue,Li[12]),t.ansi[13]=It(e.brightMagenta,Li[13]),t.ansi[14]=It(e.brightCyan,Li[14]),t.ansi[15]=It(e.brightWhite,Li[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)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=class extends ht{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=X2[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*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Ps(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+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*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Ps(i):a&2097151?(this._combined[t]=Ps(a&2097151)+Ps(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+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*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+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 f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}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 Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;czo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function zo(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 _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._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(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Pi={},pa=Pi.B;Pi[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Pi.A={"#":"£"};Pi.B=void 0;Pi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Pi.C=Pi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Pi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Pi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Pi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Pi.E=Pi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Pi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Pi.H=Pi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=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=Ti.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=or.fromCharData([0,Oy,1,0]),this._whitespaceCell=or.fromCharData([0,Hs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(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 Nu),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 Nu),this._whitespaceCell}getBlankLine(e,t){return new ko(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&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ti);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 Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ti),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 ko(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=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ti),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ti),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 I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let A=Math.max(M,0);E=zo(p,A,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);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 S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}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)}},nE=class extends ht{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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!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)}},v0=2,y0=1,xp=class extends ht{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,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(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))}};xp=fi([Re(0,bn)],xp);var il={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:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...il};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(ni(()=>{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 il))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in il))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=il[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=il[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:il[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 aE(e){return e==="block"||e==="underline"||e==="bar"}function Eo(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]&&Eo(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{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=Eo(Fb),this.decPrivateModes=Eo(qb)}reset(){this.modes=Eo(Fb),this.decPrivateModes=Eo(qb)}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))}};_p=fi([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={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 uf(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 hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{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(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[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)}};bp=fi([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[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]],lE=[[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]],Oi;function oE(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=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new cE;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 f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=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 Yb(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 mo=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)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 vp;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>mo?mo: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>mo?mo: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,mo):t}},go=[],dE=class{constructor(){this._state=0,this._active=go,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=go}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=go,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||go,!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",Iu(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=go,this._id=-1,this._state=0}}},Wn=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+=Iu(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}},xo=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=xo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=xo}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=xo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||xo,!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",Iu(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=xo,this._ident=0}},No=new S0;No.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=No,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():No,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(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=No,this._data="",this._hitLimit=!1,i));return this._params=No,this._data="",this._hitLimit=!1,t}},pE=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(ar,0,2,0),e.add(ar,8,5,8),e.add(ar,6,0,6),e.add(ar,11,0,11),e.add(ar,13,13,13),e})(),gE=class extends ht{constructor(e=mE){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 S0,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(ni(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),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[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<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 ff(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 bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Os=131072,Xb=10;function Zb(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 Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){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 HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ti.clone(),this._eraseAttrDataInternal=Ti.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 yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!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(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Wn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Wn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Wn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Wn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Wn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Wn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Wn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Wn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Wn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Wn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Wn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Wn(f=>this.restoreCursorColor(f))),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 f in Pi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}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"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} 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>Os&&(o=this._parseStack.position+Os)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthOs)for(let f=o;f0&&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,L=this._activeBuffer.x-M;for(this._activeBuffer.x=M,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),M>0&&x instanceof ko&&x.copyCellsFrom(E,L,0,M,!1);L=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,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=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Wn(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 f=1;f0||(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:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=$o.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=Ti.fg,e.bg=Ti.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|=Ti.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ti.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|=Ti.fg&16777215,s.bg&=-67108864,s.bg|=Ti.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=Ti.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(!Zb(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>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&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(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(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=Kb(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=Ti.clone(),this._eraseAttrDataInternal=Ti.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 or;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)}},yp=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&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=fi([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{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>SE)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>=tv?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>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(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()}},Sp=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)))}};Sp=fi([Re(0,_n)],Sp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new fl),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 K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(sn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(sn.forward(this._bufferService.onResize,this._onResize)),this._register(sn.forward(this.coreService.onData,this._onData)),this._register(sn.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 CE((t,i)=>this._inputHandler.parse(t,i))),this._register(sn.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&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!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,v0),t=Math.max(t,y0),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(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ni(()=>{for(let t of e)t.dispose()})}}},EE={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 NE(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=EE[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,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=pe.ESC+f}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 bi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,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||(bi=this._search(t),bi===-1)||this._getKey(this._array[bi])!==t)return!1;do if(this._array[bi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(bi),!0;while(++bia-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&&(bi=this._search(e),!(bi<0||bi>=this._array.length)&&this._getKey(this._array[bi])===e))do yield this._array[bi];while(++bi=this._array.length)&&this._getKey(this._array[bi])===e))do t(this._array[bi]);while(++bi=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}},pf=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(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(ni(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(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{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&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)}},rv=20,Du=class extends ht{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 DE(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(Ke(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ni(()=>{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===rv+1&&(this._liveRegion.textContent+=$f.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(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}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:f})=>{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=f=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;xa(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(Ke(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ke(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ke(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ke(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 f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.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 f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_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&&ME(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,xa(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}}};wp=fi([Re(1,Wp),Re(2,ls),Re(3,_n),Re(4,qy)],wp);function ME(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 BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new fl),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new fl),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(TE),this._instantiationService.setService(Fo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),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(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ni(()=>{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=ti.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ai.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ai.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(Du,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(Ke(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ke(this.textarea,"paste",e)),this._register(Ke(this.element,"paste",e)),u0?this._register(Ke(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ke(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ke(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ke(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ke(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ke(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ke(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ke(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ke(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ke(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(Ke(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",Uf.get()),f0||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(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(as,this._coreBrowserService),this._register(Ke(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ke(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(gl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(ls,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(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,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(ap,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(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,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(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ke(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(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,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 S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.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=S<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(Ke(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(Ke(t,"wheel",o=>{var c,h,p,f,_;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,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.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){By(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=NE(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)&&(LE(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 or)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=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 zE(t)}getNullCell(){return new or}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(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)}},IE=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)}},HE=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}},UE=["cols","rows"],Er=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),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(UE.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 IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(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 PE(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 Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT @@ -94,48 +94,48 @@ 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 Wi=0,Gi=0,Yi=0,di=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(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})(cn||(cn={}));var GE;(e=>{function t(p,f){if(di=(f.rgba&255)/255,di===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Wi=v+Math.round((_-v)*di),Gi=S+Math.round((x-S)*di),Yi=N+Math.round((b-N)*di);let M=cn.toCss(Wi,Gi,Yi),E=cn.toRgba(Wi,Gi,Yi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Wi,Gi,Yi]=Su.toChannels(f),{css:cn.toCss(Wi,Gi,Yi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[Wi,Gi,Yi]=Su.toChannels(p.rgba),{css:cn.toCss(Wi,Gi,Yi,di),rgba:cn.toRgba(Wi,Gi,Yi,di)}}e.opacity=o;function c(p,f){return di=p.rgba&255,o(p,di*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var nn;(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 Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Wi,Gi,Yi);case 5:return Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),di=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Wi,Gi,Yi,di);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 Wi=parseInt(o[1]),Gi=parseInt(o[2]),Yi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Wi,Gi,Yi,di);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),[Wi,Gi,Yi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Wi,Gi,Yi,di),css:a}}e.toColor=s})(nn||(nn={}));var mn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(di=(h&255)/255,di===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Wi=x+Math.round((p-x)*di),Gi=b+Math.round((f-b)*di),Yi=v+Math.round((_-v)*di),cn.toRgba(Wi,Gi,Yi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(is(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=is(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,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})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function is(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.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:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!ns(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&ns(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&ns(c,p)&&ns(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=!C0(e,t),a=!ns(e,t),o=!k0(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?!ns(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(ns(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&&(ns(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!ns(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",el="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${el}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${el}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${el}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${el}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${el}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${el}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,qs="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(qs)||s.createObjectStore(qs)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function tl(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction(qs,"readwrite");c.objectStore(qs).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction(qs,"readonly").objectStore(qs).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction(qs,"readwrite");a.objectStore(qs).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Oi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[O,I]=w.useState(new Set),[A,q]=w.useState(null),[R,re]=w.useState(null),[ue,ye]=w.useState(!1),[B,se]=w.useState(!1),$=eN(x,_),G=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const H=w.useCallback(K=>{var ge;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[he,ge]of Oi)ge.container.style.display=he===K?"block":"none";if(K){const he=Oi.get(K);he&&setTimeout(()=>H(he),50)}},[H]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const F=w.useRef({});w.useEffect(()=>{F.current=f||{}},[f]);const xe=w.useCallback((K,he,ge)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",ze=z.current[K]?"&bypass=true":"",Fe=F.current[K],we=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${ze}${we}`);He.onopen=()=>{he.connected=!0,he._retried=!1,I(st=>{const it=new Set(st);return it.delete(K),it}),He.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let tt=!0;He.onmessage=st=>{if(tt&&(tt=!1,typeof st.data=="string"&&st.data===QE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof st.data=="string"?lv(st.data):st.data)},He.onclose=st=>{if(he.connected=!1,he.ws===He){he.ws=null;try{const it=he.serialize.serialize();tl(K,it).catch(()=>{})}catch{}if(st.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r + */var Gi=0,Yi=0,Vi=0,di=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(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})(cn||(cn={}));var GE;(e=>{function t(p,f){if(di=(f.rgba&255)/255,di===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Gi=v+Math.round((_-v)*di),Yi=S+Math.round((x-S)*di),Vi=N+Math.round((b-N)*di);let M=cn.toCss(Gi,Yi,Vi),E=cn.toRgba(Gi,Yi,Vi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Gi,Yi,Vi]=Su.toChannels(f),{css:cn.toCss(Gi,Yi,Vi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[Gi,Yi,Vi]=Su.toChannels(p.rgba),{css:cn.toCss(Gi,Yi,Vi,di),rgba:cn.toRgba(Gi,Yi,Vi,di)}}e.opacity=o;function c(p,f){return di=p.rgba&255,o(p,di*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var nn;(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 Gi=parseInt(a.slice(1,2).repeat(2),16),Yi=parseInt(a.slice(2,3).repeat(2),16),Vi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Gi,Yi,Vi);case 5:return Gi=parseInt(a.slice(1,2).repeat(2),16),Yi=parseInt(a.slice(2,3).repeat(2),16),Vi=parseInt(a.slice(3,4).repeat(2),16),di=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Gi,Yi,Vi,di);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 Gi=parseInt(o[1]),Yi=parseInt(o[2]),Vi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Gi,Yi,Vi,di);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),[Gi,Yi,Vi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Gi,Yi,Vi,di),css:a}}e.toColor=s})(nn||(nn={}));var mn;(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,f=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 f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(di=(h&255)/255,di===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Gi=x+Math.round((p-x)*di),Yi=b+Math.round((f-b)*di),Vi=v+Math.round((_-v)*di),cn.toRgba(Gi,Yi,Vi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(is(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=is(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,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})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function is(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.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:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=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 f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!ns(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),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&ns(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&ns(c,p)&&ns(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=!C0(e,t),a=!ns(e,t),o=!k0(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?!ns(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(ns(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&&(ns(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{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}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}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(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,f=t.scrollback,_=f===void 0?p:av(f+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 w0{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=YE}_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=!C0(e,t),a=!ns(e,t),o=!k0(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+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",nl="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${nl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${nl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${nl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${nl}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={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"},iN="plotlink-terminal",nN=1,$s="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains($s)||s.createObjectStore($s)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function rl(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction($s,"readwrite");c.objectStore($s).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction($s,"readonly").objectStore($s).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction($s,"readwrite");a.objectStore($s).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const zi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[L,I]=w.useState(new Set),[A,q]=w.useState(null),[R,ne]=w.useState(null),[ue,ye]=w.useState(!1),[B,re]=w.useState(!1),$=eN(x,_),G=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const H=w.useCallback(K=>{var ge;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[he,ge]of zi)ge.container.style.display=he===K?"block":"none";if(K){const he=zi.get(K);he&&setTimeout(()=>H(he),50)}},[H]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const F=w.useRef({});w.useEffect(()=>{F.current=f||{}},[f]);const xe=w.useCallback((K,he,ge)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",ze=z.current[K]?"&bypass=true":"",Fe=F.current[K],we=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${ze}${we}`);He.onopen=()=>{he.connected=!0,he._retried=!1,I(st=>{const nt=new Set(st);return nt.delete(K),nt}),He.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let it=!0;He.onmessage=st=>{if(it&&(it=!1,typeof st.data=="string"&&st.data===QE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof st.data=="string"?lv(st.data):st.data)},He.onclose=st=>{if(he.connected=!1,he.ws===He){he.ws=null;try{const nt=he.serialize.serialize();rl(K,nt).catch(()=>{})}catch{}if(st.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),V.current(K,he,!1);return}I(it=>new Set(it).add(K))}},he.term.onData(st=>{He.readyState===WebSocket.OPEN&&He.send(st)}),he.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,he)=>{if(!S.current||Oi.has(K))return;const{resume:ge=!1,autoConnect:De=!0}=he??{},ze=document.createElement("div");ze.style.width="100%",ze.style.height="100%",ze.style.display="none",ze.style.paddingLeft="10px",ze.style.boxSizing="border-box",S.current.appendChild(ze);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),we=new WE,He=new XE;Fe.loadAddon(we),Fe.loadAddon(He),Fe.open(ze);const tt={term:Fe,fit:we,serialize:He,ws:null,container:ze,observer:null,connected:!1},st=new ResizeObserver(()=>{var Nt;const{width:it}=ze.getBoundingClientRect();if(!(it<50))try{we.fit(),((Nt=tt.ws)==null?void 0:Nt.readyState)===WebSocket.OPEN&&tt.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});st.observe(ze),tt.observer=st,Oi.set(K,tt),E(it=>[...it,K]);try{const it=await rN(K);if(it){const Nt=lv(it);Fe.write(Nt),Nt!==it&&tl(K,Nt).catch(()=>{})}}catch{}De?xe(K,tt,ge):I(it=>new Set(it).add(K)),setTimeout(()=>H(tt),50)},[xe,H]),D=w.useCallback(async(K,he)=>{const ge=Oi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,he))},[xe]),X=w.useCallback(K=>{const he=Oi.get(K);if(he){try{const ge=he.serialize.serialize();tl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Oi.delete(K),E(ge=>ge.filter(De=>De!==K)),I(ge=>{const De=new Set(ge);return De.delete(K),De}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const he=Oi.get(K);he&&(((ge=he.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&he.ws.send(`exit -`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Oi.delete(K),E(De=>De.filter(ze=>ze!==K)),I(De=>{const ze=new Set(De);return ze.delete(K),ze}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,he,ge)=>{const De=Oi.get(K);if(!De||Oi.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,...ge??{}})})).ok)return!1;Oi.delete(K),Oi.set(he,De);try{const Fe=De.serialize.serialize();await mf(K),await tl(he,Fe)}catch{}return E(Fe=>Fe.map(we=>we===K?he:we)),I(Fe=>{if(!Fe.has(K))return Fe;const we=new Set(Fe);return we.delete(K),we.add(he),we}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),V.current(he,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if($){T(null);return}if(G){T(null);return}Oi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Oi.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!he}),T(t)}}).catch(()=>{Oi.has(t)||(j(t),T(t))})}},[t,j,T,$,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,ge]of Oi)if(ge.connected)try{const De=ge.serialize.serialize();tl(he,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of Oi){try{const ge=he.serialize.serialize();tl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Oi.clear()},[]);const ae=t?O.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>re(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!$&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),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:ue?"Copied!":"Copy"})]})]})]})}),G&&!$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){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:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>re(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;re(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Wo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Wo.prototype.normal={};Wo.prototype.property={};Wo.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Wo(i,s,t)}function Cp(e){return e.toLowerCase()}class Tn{constructor(t,i){this.attribute=i,this.property=t}}Tn.prototype.attribute="";Tn.prototype.booleanish=!1;Tn.prototype.boolean=!1;Tn.prototype.commaOrSpaceSeparated=!1;Tn.prototype.commaSeparated=!1;Tn.prototype.defined=!1;Tn.prototype.mustUseProperty=!1;Tn.prototype.number=!1;Tn.prototype.overloadedBoolean=!1;Tn.prototype.property="";Tn.prototype.spaceSeparated=!1;Tn.prototype.space=void 0;let dN=0;const lt=ya(),ji=ya(),kp=ya(),Se=ya(),Zt=ya(),ll=ya(),qn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:ji,commaOrSpaceSeparated:qn,commaSeparated:ll,number:Se,overloadedBoolean:kp,spaceSeparated:Zt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Tn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var il={},xf,pv;function wN(){if(pv)return xf;pv=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=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var O=1,I=1;function A(V){var H=V.match(t);H&&(O+=H.length);var T=V.lastIndexOf(p);I=~T?V.length-T:I+V.length}function q(){var V={line:O,column:I};return function(H){return H.position=new R(V),ye(),H}}function R(V){this.start=V,this.end={line:O,column:I},this.source=E.source}R.prototype.content=M;function re(V){var H=new Error(E.source+":"+O+":"+I+": "+V);if(H.reason=V,H.filename=E.source,H.line=O,H.column=I,H.source=M,!E.silent)throw H}function ue(V){var H=V.exec(M);if(H){var T=H[0];return A(T),M=M.slice(T.length),H}}function ye(){ue(i)}function B(V){var H;for(V=V||[];H=se();)H!==!1&&V.push(H);return V}function se(){var V=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var H=2;x!=M.charAt(H)&&(_!=M.charAt(H)||f!=M.charAt(H+1));)++H;if(H+=2,x===M.charAt(H-1))return re("End of comment missing");var T=M.slice(2,H-2);return I+=2,A(T),M=M.slice(H),I+=2,V({type:b,comment:T})}}function $(){var V=q(),H=ue(s);if(H){if(se(),!ue(a))return re("property missing ':'");var T=ue(o),z=V({type:v,property:N(H[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return ue(c),z}}function G(){var V=[];B(V);for(var H;H=$();)H!==!1&&(V.push(H),B(V));return V}return ye(),G()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return il;mv=1;var e=il&&il.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(il,"__esModule",{value:!0}),il.default=i;const t=e(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return il}var xo={},gv;function kN(){if(gv)return xo;gv=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return xo.camelCase=p,xo}var _o,xv;function EN(){if(xv)return _o;xv=1;var e=_o&&_o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,_o=s,_o}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(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 L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ao(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class hn 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=Ao(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}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}zo(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);zo(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 zo(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 zo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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?(Wn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(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 xn=Ws(/[A-Za-z]/),un=Ws(/[\dA-Za-z]/),JN=Ws(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=Ws(/\d/),e5=Ws(/[\dA-Fa-f]/),t5=Ws(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function Ft(e){return e!==null&&(e<0||e===32)}function mt(e){return e===-2||e===-1||e===32}const Fu=Ws(new RegExp("\\p{P}|\\p{S}","u")),ba=Ws(/\s/);function Ws(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function gl(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 yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return mt(p)?(e.enter(i),h(p)):t(p)}function h(p){return mt(p)&&o++c))return;const re=t.events.length;let ue=re,ye,B;for(;ue--;)if(t.events[ue][0]==="exit"&&t.events[ue][1].type==="chunkFlow"){if(ye){B=t.events[ue][1].end;break}ye=!0}for(E(s),R=re;RI;){const q=i[A];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function O(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function hl(e){if(e===null||Ft(e)||ba(e))return 1;if(Fu(e))return 2}function qu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=sr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=sr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=sr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=sr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=sr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Wn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&mt(R)?yt(e,O,"linePrefix",o+1)(R):O(R)}function O(R){return R===null||Ye(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),O(R)):(e.consume(R),I)}function A(R){return e.exit("codeFenced"),t(R)}function q(R,re,ue){let ye=0;return B;function B(H){return R.enter("lineEnding"),R.consume(H),R.exit("lineEnding"),se}function se(H){return R.enter("codeFencedFence"),mt(H)?yt(R,$,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):$(H)}function $(H){return H===h?(R.enter("codeFencedFenceSequence"),G(H)):ue(H)}function G(H){return H===h?(ye++,R.consume(H),G):ye>=c?(R.exit("codeFencedFenceSequence"),mt(H)?yt(R,V,"whitespace")(H):V(H)):ue(H)}function V(H){return H===null||Ye(H)?(R.exit("codeFencedFence"),re(H)):ue(H)}}}function _5(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 bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(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):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&bo(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),bo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bo(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Mu(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(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):Ye(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||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!mt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ro(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):mt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.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)?Ro(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return mt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return Ft(h)?Ro(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return mt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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"},Wn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(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||Ye(_)?(e.exit("atxHeading"),t(_)):mt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Ft(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:$:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||Ft(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):$(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):$(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?O(C):I(C))}return C===45||un(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:$):i(C)}function O(C){return mt(C)?(e.consume(C),O):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):mt(C)?(e.consume(C),I):B(C)}function A(C){return C===45||C===46||C===58||C===95||un(C)?(e.consume(C),A):q(C)}function q(C){return C===61?(e.consume(C),R):mt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,re):mt(C)?(e.consume(C),R):ue(C)}function re(C){return C===p?(e.consume(C),p=null,ye):C===null||Ye(C)?i(C):(e.consume(C),re)}function ue(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),ue)}function ye(C){return C===47||C===62||mt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),se):i(C)}function se(C){return C===null||Ye(C)?$(C):mt(C)?(e.consume(C),se):i(C)}function $(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),$)}function G(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),H}function H(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),$(C))}function T(C){return C===45?(e.consume(C),j):$(C)}function z(C){return C===47?(e.consume(C),c="",F):$(C)}function F(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):$(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),F):$(C)}function xe(C){return C===93?(e.consume(C),j):$(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):$(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Go,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),q):j===63?(e.consume(j),I):xn(j)?(e.consume(j),ue):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),O):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):Ye(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):Ye(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function O(j){return j===null||j===62?T(j):Ye(j)?(c=O,z(j)):(e.consume(j),O)}function I(j){return j===null?i(j):j===63?(e.consume(j),A):Ye(j)?(c=I,z(j)):(e.consume(j),I)}function A(j){return j===62?T(j):I(j)}function q(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||un(j)?(e.consume(j),R):re(j)}function re(j){return Ye(j)?(c=re,z(j)):mt(j)?(e.consume(j),re):T(j)}function ue(j){return j===45||un(j)?(e.consume(j),ue):j===47||j===62||Ft(j)?ye(j):i(j)}function ye(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):Ye(j)?(c=ye,z(j)):mt(j)?(e.consume(j),ye):T(j)}function B(j){return j===45||j===46||j===58||j===95||un(j)?(e.consume(j),B):se(j)}function se(j){return j===61?(e.consume(j),$):Ye(j)?(c=se,z(j)):mt(j)?(e.consume(j),se):ye(j)}function $(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,G):Ye(j)?(c=$,z(j)):mt(j)?(e.consume(j),$):(e.consume(j),V)}function G(j){return j===a?(e.consume(j),a=void 0,H):j===null?i(j):Ye(j)?(c=G,z(j)):(e.consume(j),G)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||Ft(j)?ye(j):(e.consume(j),V)}function H(j){return j===47||j===62||Ft(j)?ye(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),F}function F(j){return mt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),mt(f)?yt(e,h,"whitespace")(f):h(f))}}const jn={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Go,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return mt(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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Go,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!mt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(jn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(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!mt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),mt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Go,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++inew Set(nt).add(K))}},he.term.onData(st=>{He.readyState===WebSocket.OPEN&&He.send(st)}),he.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,he)=>{if(!S.current||zi.has(K))return;const{resume:ge=!1,autoConnect:De=!0}=he??{},ze=document.createElement("div");ze.style.width="100%",ze.style.height="100%",ze.style.display="none",ze.style.paddingLeft="10px",ze.style.boxSizing="border-box",S.current.appendChild(ze);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),we=new WE,He=new XE;Fe.loadAddon(we),Fe.loadAddon(He),Fe.open(ze);const it={term:Fe,fit:we,serialize:He,ws:null,container:ze,observer:null,connected:!1},st=new ResizeObserver(()=>{var Nt;const{width:nt}=ze.getBoundingClientRect();if(!(nt<50))try{we.fit(),((Nt=it.ws)==null?void 0:Nt.readyState)===WebSocket.OPEN&&it.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});st.observe(ze),it.observer=st,zi.set(K,it),E(nt=>[...nt,K]);try{const nt=await rN(K);if(nt){const Nt=lv(nt);Fe.write(Nt),Nt!==nt&&rl(K,Nt).catch(()=>{})}}catch{}De?xe(K,it,ge):I(nt=>new Set(nt).add(K)),setTimeout(()=>H(it),50)},[xe,H]),D=w.useCallback(async(K,he)=>{const ge=zi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,he))},[xe]),X=w.useCallback(K=>{const he=zi.get(K);if(he){try{const ge=he.serialize.serialize();rl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(K),E(ge=>ge.filter(De=>De!==K)),I(ge=>{const De=new Set(ge);return De.delete(K),De}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const he=zi.get(K);he&&(((ge=he.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(K),E(De=>De.filter(ze=>ze!==K)),I(De=>{const ze=new Set(De);return ze.delete(K),ze}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,he,ge)=>{const De=zi.get(K);if(!De||zi.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,...ge??{}})})).ok)return!1;zi.delete(K),zi.set(he,De);try{const Fe=De.serialize.serialize();await mf(K),await rl(he,Fe)}catch{}return E(Fe=>Fe.map(we=>we===K?he:we)),I(Fe=>{if(!Fe.has(K))return Fe;const we=new Set(Fe);return we.delete(K),we.add(he),we}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),V.current(he,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if($){T(null);return}if(G){T(null);return}zi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!zi.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!he}),T(t)}}).catch(()=>{zi.has(t)||(j(t),T(t))})}},[t,j,T,$,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,ge]of zi)if(ge.connected)try{const De=ge.serialize.serialize();rl(he,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of zi){try{const ge=he.serialize.serialize();rl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}zi.clear()},[]);const ae=t?L.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.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))?d.jsx("button",{onClick:()=>ne(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]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!$&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.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?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.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:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),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:ue?"Copied!":"Copy"})]})]})]})}),G&&!$&&d.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:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.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."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){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:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ne(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;ne(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Go{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Go.prototype.normal={};Go.prototype.property={};Go.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Go(i,s,t)}function Cp(e){return e.toLowerCase()}class Dn{constructor(t,i){this.attribute=i,this.property=t}}Dn.prototype.attribute="";Dn.prototype.booleanish=!1;Dn.prototype.boolean=!1;Dn.prototype.commaOrSpaceSeparated=!1;Dn.prototype.commaSeparated=!1;Dn.prototype.defined=!1;Dn.prototype.mustUseProperty=!1;Dn.prototype.number=!1;Dn.prototype.overloadedBoolean=!1;Dn.prototype.property="";Dn.prototype.spaceSeparated=!1;Dn.prototype.space=void 0;let dN=0;const lt=ya(),ji=ya(),kp=ya(),Se=ya(),Xt=ya(),ul=ya(),Gn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:ji,commaOrSpaceSeparated:Gn,commaSeparated:ul,number:Se,overloadedBoolean:kp,spaceSeparated:Xt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Dn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var sl={},xf,pv;function wN(){if(pv)return xf;pv=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=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var L=1,I=1;function A(V){var H=V.match(t);H&&(L+=H.length);var T=V.lastIndexOf(p);I=~T?V.length-T:I+V.length}function q(){var V={line:L,column:I};return function(H){return H.position=new R(V),ye(),H}}function R(V){this.start=V,this.end={line:L,column:I},this.source=E.source}R.prototype.content=M;function ne(V){var H=new Error(E.source+":"+L+":"+I+": "+V);if(H.reason=V,H.filename=E.source,H.line=L,H.column=I,H.source=M,!E.silent)throw H}function ue(V){var H=V.exec(M);if(H){var T=H[0];return A(T),M=M.slice(T.length),H}}function ye(){ue(i)}function B(V){var H;for(V=V||[];H=re();)H!==!1&&V.push(H);return V}function re(){var V=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var H=2;x!=M.charAt(H)&&(_!=M.charAt(H)||f!=M.charAt(H+1));)++H;if(H+=2,x===M.charAt(H-1))return ne("End of comment missing");var T=M.slice(2,H-2);return I+=2,A(T),M=M.slice(H),I+=2,V({type:b,comment:T})}}function $(){var V=q(),H=ue(s);if(H){if(re(),!ue(a))return ne("property missing ':'");var T=ue(o),z=V({type:v,property:N(H[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return ue(c),z}}function G(){var V=[];B(V);for(var H;H=$();)H!==!1&&(V.push(H),B(V));return V}return ye(),G()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return sl;mv=1;var e=sl&&sl.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(sl,"__esModule",{value:!0}),sl.default=i;const t=e(wN());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:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return sl}var _o={},gv;function kN(){if(gv)return _o;gv=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return _o.camelCase=p,_o}var bo,xv;function EN(){if(xv)return bo;xv=1;var e=bo&&bo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();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,bo=s,bo}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(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 L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ro(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class hn 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=Ro(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}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(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=UN(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=HN(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"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(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)}Po(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Po(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(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 $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.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 FN(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 Po(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 Po(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;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?(Yn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(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 xr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const xn=Fs(/[A-Za-z]/),un=Fs(/[\dA-Za-z]/),JN=Fs(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=Fs(/\d/),e5=Fs(/[\dA-Fa-f]/),t5=Fs(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function mt(e){return e===-2||e===-1||e===32}const Fu=Fs(new RegExp("\\p{P}|\\p{S}","u")),ba=Fs(/\s/);function Fs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function bl(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 yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return mt(p)?(e.enter(i),h(p)):t(p)}function h(p){return mt(p)&&o++c))return;const ne=t.events.length;let ue=ne,ye,B;for(;ue--;)if(t.events[ue][0]==="exit"&&t.events[ue][1].type==="chunkFlow"){if(ye){B=t.events[ue][1].end;break}ye=!0}for(E(s),R=ne;RI;){const q=i[A];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function L(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function pl(e){if(e===null||qt(e)||ba(e))return 1;if(Fu(e))return 2}function qu(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};Cv(x,-p),Cv(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},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=lr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=lr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=lr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=lr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=lr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Yn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&mt(R)?yt(e,L,"linePrefix",o+1)(R):L(R)}function L(R){return R===null||Ye(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),L(R)):(e.consume(R),I)}function A(R){return e.exit("codeFenced"),t(R)}function q(R,ne,ue){let ye=0;return B;function B(H){return R.enter("lineEnding"),R.consume(H),R.exit("lineEnding"),re}function re(H){return R.enter("codeFencedFence"),mt(H)?yt(R,$,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):$(H)}function $(H){return H===h?(R.enter("codeFencedFenceSequence"),G(H)):ue(H)}function G(H){return H===h?(ye++,R.consume(H),G):ye>=c?(R.exit("codeFencedFenceSequence"),mt(H)?yt(R,V,"whitespace")(H):V(H)):ue(H)}function V(H){return H===null||Ye(H)?(R.exit("codeFencedFence"),ne(H)):ue(H)}}}function _5(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 bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(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):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(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&&vo(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),vo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),vo(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 Y0(e,t,i,s,a,o,c,h,p){const f=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||Mu(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||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||qt(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):Ye(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||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!mt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(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),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Do(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):mt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=xr(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)?Do(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return mt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return qt(h)?Do(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return mt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(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"},Yn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(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||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):mt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["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"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(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 Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(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:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:$:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||qt(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):$(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):$(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?L(C):I(C))}return C===45||un(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:$):i(C)}function L(C){return mt(C)?(e.consume(C),L):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):mt(C)?(e.consume(C),I):B(C)}function A(C){return C===45||C===46||C===58||C===95||un(C)?(e.consume(C),A):q(C)}function q(C){return C===61?(e.consume(C),R):mt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ne):mt(C)?(e.consume(C),R):ue(C)}function ne(C){return C===p?(e.consume(C),p=null,ye):C===null||Ye(C)?i(C):(e.consume(C),ne)}function ue(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),ue)}function ye(C){return C===47||C===62||mt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),re):i(C)}function re(C){return C===null||Ye(C)?$(C):mt(C)?(e.consume(C),re):i(C)}function $(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),$)}function G(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),H}function H(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),$(C))}function T(C){return C===45?(e.consume(C),j):$(C)}function z(C){return C===47?(e.consume(C),c="",F):$(C)}function F(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):$(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),F):$(C)}function xe(C){return C===93?(e.consume(C),j):$(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):$(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(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 K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Yo,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),q):j===63?(e.consume(j),I):xn(j)?(e.consume(j),ue):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),L):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):Ye(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):Ye(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function L(j){return j===null||j===62?T(j):Ye(j)?(c=L,z(j)):(e.consume(j),L)}function I(j){return j===null?i(j):j===63?(e.consume(j),A):Ye(j)?(c=I,z(j)):(e.consume(j),I)}function A(j){return j===62?T(j):I(j)}function q(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||un(j)?(e.consume(j),R):ne(j)}function ne(j){return Ye(j)?(c=ne,z(j)):mt(j)?(e.consume(j),ne):T(j)}function ue(j){return j===45||un(j)?(e.consume(j),ue):j===47||j===62||qt(j)?ye(j):i(j)}function ye(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):Ye(j)?(c=ye,z(j)):mt(j)?(e.consume(j),ye):T(j)}function B(j){return j===45||j===46||j===58||j===95||un(j)?(e.consume(j),B):re(j)}function re(j){return j===61?(e.consume(j),$):Ye(j)?(c=re,z(j)):mt(j)?(e.consume(j),re):ye(j)}function $(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,G):Ye(j)?(c=$,z(j)):mt(j)?(e.consume(j),$):(e.consume(j),V)}function G(j){return j===a?(e.consume(j),a=void 0,H):j===null?i(j):Ye(j)?(c=G,z(j)):(e.consume(j),G)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||qt(j)?ye(j):(e.consume(j),V)}function H(j){return j===47||j===62||qt(j)?ye(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),F}function F(j){return mt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),mt(f)?yt(e,h,"whitespace")(f):h(f))}}const Rn={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(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 S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(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"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Yo,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return mt(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 gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Yo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!mt(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(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(Rn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(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 _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(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!mt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(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 yj(e,t,i){const s=this;let a;return o;function o(f){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=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),mt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Yo,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,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 Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj: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 f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){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 Hj(e,t){let i=-1;const s=[];let a;for(;++i0){const Wt=Me.tokenStack[Me.tokenStack.length-1];(Wt[1]||Av).call(Me,void 0,Wt[0])}for(be.position={start:Is(ee.length>0?ee[0][1].start:{line:1,column:1,offset:0}),end:Is(ee.length>0?ee[ee.length-2][1].end:{line:1,column:1,offset:0})},Xe=-1;++Xe0){const Gt=Me.tokenStack[Me.tokenStack.length-1];(Gt[1]||Av).call(Me,void 0,Gt[0])}for(be.position={start:zs(ee.length>0?ee[0][1].start:{line:1,column:1,offset:0}),end:zs(ee.length>0?ee[ee.length-2][1].end:{line:1,column:1,offset:0})},Xe=-1;++Xe0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=gl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:gl(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 aT(e,t){const i={src:gl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:gl(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 cT(e,t){const i={href:gl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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(;++h0&&(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 eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=bl(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 f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(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 rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(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 sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:bl(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 aT(e,t){const i={src:bl(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 lT(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 oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:bl(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 cT(e,t){const i={href:bl(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 uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(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 dT(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=nm(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Do=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 Wu:case iS:return i(c,a);case Do:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),nl="",{toString:CT}={},{keys:kT}=Object,vo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Do,nl];case"Object":return[Bu,nl];case"Date":return[um,nl];case"RegExp":return[hm,nl];case"Map":return[dm,nl];case"Set":return[fm,nl];case"DataView":return[Do,i]}return i.includes("Array")?[Do,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(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]=vo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Do:{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 Bu:{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 kT(c))(e||!cu(vo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(vo(b))||cu(vo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(vo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Po=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let O=typeof i=="string"?i:i(p,v);typeof O=="string"&&(O={type:"text",value:O}),S.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(O)?O:[O]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const O=M.children[M.children.length-1];O&&O.type==="text"?O.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Po(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`});const f={type:"element",tagName:"li",properties:o,children:c};return e.patch(t,f),e.applyData(t,f)}function hT(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const i=e.children;let s=-1;for(;!t&&++s1}function dT(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=nm(t.children[1]),p=M0(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 xT(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 f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Mo=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(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 Wu:case iS:return i(c,a);case Mo:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS: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 Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),al="",{toString:CT}={},{keys:kT}=Object,yo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Mo,al];case"Object":return[Bu,al];case"Date":return[um,al];case"RegExp":return[hm,al];case"Map":return[dm,al];case"Set":return[fm,al];case"DataView":return[Mo,i]}return i.includes("Array")?[Mo,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(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]=yo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Mo:{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 Bu:{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 kT(c))(e||!cu(yo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(yo(b))||cu(yo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(yo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Io=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(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 jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let L=typeof i=="string"?i:i(p,v);typeof L=="string"&&(L={type:"text",value:L}),S.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 M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const L=M.children[M.children.length-1];L&&L.type==="text"?L.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Io(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 Gu=(function(e){if(e==null)return MT;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?AT(e):RT(e);if(typeof e=="string")return DT(e);throw new Error("Expected function, string, or object as test")});function AT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` `}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var yf,Hv;function WT(){if(Hv)return yf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,O=!1;for(typeof N=="boolean"&&(O=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Yo(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 XT(e){if(Yo(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 ZT(e){Yo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 Yo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&O.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?O.push(...R):R&&O.push(R),S=A+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(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 $A(e){this.exit(e)}function FA(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 qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(O)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=O),v[x]=O),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,L=!1;for(typeof N=="boolean"&&(L=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;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 jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Vo(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 XT(e){if(Vo(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 ZT(e){Vo(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 QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(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 Vo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(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 rA(e)}function rA(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,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(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 $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{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 oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,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 _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),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 _A(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||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&L.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?L.push(...R):R&&L.push(R),S=A+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(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 hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=xr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function $A(e){this.exit(e)}function FA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=xr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function qA(e){this.exit(e)}function WA(){return"["}function dS(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 GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=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?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(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 eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(L)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=L),v[x]=L),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(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 oR(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 cR(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 uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=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),f(),_}function hR(e,t,i){return(i?"":" ")+e}function gm(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 dR(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Io(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=hl(e),a=hl(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(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 Ho(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=pl(e),a=pl(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}}mS.peek=pR;function mS(e,t,i,s){const a=fR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` `,after:` `});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 f=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(f)&&(f=Io(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function xm(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 wR(e){const t=xm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):xm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Io(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Io(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Df,tableHeader:Df,tableRow:Df}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),O=f([E]);return O.slice(0,O.indexOf(` -`))}function p(v,S,N,M){const E=N.enter("tableCell"),O=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return O(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const O=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=pr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(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?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||Ft(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Ft(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Go,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=hl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[se][1].type;if(V==="lineEnding"||V==="linePrefix")se--;else break}const $=se>-1?s.events[se][1].type:null,G=$==="tableHead"||$==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):mt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||Ft(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,mt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return mt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?A(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),O(B)):q(B)}function O(B){return B===45?(e.consume(B),O):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return mt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),re(B)}function re(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),re):B===null||Ye(B)?(e.exit("tableRow"),t(B)):mt(B)?yt(e,re,"whitespace")(B):(e.enter("data"),ue(B))}function ue(B){return B===null||B===124||Ft(B)?(e.exit("data"),re(B)):(e.consume(B),B===92?ye:ue)}function ye(B){return B===92||B===124?(e.consume(B),ue):ue(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},rl(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=rl(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 rl(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Ye(p)?t(p):mt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],dl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["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"]},Us={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...dl,...t}:dl,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Vo(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Vo(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Us.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const ol=["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"],rs=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(ol.map(e=>[IS(e),e])),P3={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 Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 No(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,O=Math.max(1,_-E),I=a.fontWeight??400,A=iy((re,ue)=>e(re,ue,I),t,f,N),q=A.length*N*o,R=A.every(re=>e(re,N,I)<=f+.5);return{lines:A,ok:q<=O&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function cl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=cl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=cl(t.lineHeightFactor,.9,2),c=cl(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 Vu(e){if(!e||typeof e!="object")return;const t=e,i=cl(t.paddingX,0,.25),s=cl(t.paddingY,0,.25),a=cl(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 jo(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(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 $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:O,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:O-I,y:E},base2:{x:O+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 du=.05;function Vi(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Vi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Vi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Vi(t.x)&&Vi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Vi(b.x)&&Vi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Vi(t.x)&&Vi(t.y)&&Vi(t.width)&&Vi(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function n4(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=vm(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=Vu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Vi(e==null?void 0:e.x)&&Vi(e==null?void 0:e.y)&&Vi(e==null?void 0:e.width)&&Vi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 yo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(O=>!_[O]),v=O=>s.needClean>0?yo(O,s.needClean):"no image cuts",S={plan:yo(s.total,s.total),clean:v(s.withClean),letter:yo(s.withText,s.total),export:yo(s.exported,s.total),upload:yo(s.uploaded,s.total),publish:null},N=x.map((O,I)=>({key:O,label:cD[O],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Cm=[{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:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(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 al(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==al(e.current)}function km(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Nn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,pi,Rt,St,Gt,ot,Ht;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let U=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Ce}=await uy(async()=>{const{ensureFontsReady:Ae}=await import("./export-cut-33MiJugN.js");return{ensureFontsReady:Ae}},[]);await Ce([b.family,v.family])}catch{}U||G(!0)})(),()=>{U=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),O=E.invalid.length,[I,A]=w.useState(!1),q=O===0&&E.changed&&E.overlays.length>0,[R,re]=w.useState(()=>E.overlays),[ue,ye]=w.useState(()=>al(E.overlays)),B=w.useRef(null),se=w.useCallback(U=>(Ce,Ae,Ne=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ge?(Ge.font=`${Ne} ${Ae}px ${U}`,Ge.measureText(Ce).width):Ce.length*Ae*.5},[]),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(!1),[F,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),he=w.useRef(null),ge=w.useCallback(()=>{const U=oe.current;if(!U)return;const Ce=U.clientWidth,Ae=U.clientHeight;let Ne,Ge;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ne=At.width,Ge=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ne=At.naturalWidth,Ge=At.naturalHeight}if(!Ce||!Ae)return;const Ue=Math.min(Ce/Ne,Ae/Ge),dt=Ne*Ue,_t=Ge*Ue;ae({x:(Ce-dt)/2,y:(Ae-_t)/2,width:dt,height:_t})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const U=oe.current;if(!U)return;const Ce=new ResizeObserver(()=>ge());return Ce.observe(U),()=>Ce.disconnect()},[ge]);const De=w.useCallback(U=>{const Ce=WS(U.type,U.x,U.y),Ae=Ce.width,Ne=Math.max(.08,1-U.y);if(!U.text||!$||Z.width<=0)return Ce;const Ge=U.type==="sfx"?N:S,Ue=Nn(Ae,Z.width);let dt=U.type==="sfx"?.08:.12;for(let _t=0;_t<24;_t++){const At=Math.min(dt,Ne),Bt=Nn(At,Z.height);if(!No(se(Ge),U.text,Ue,Bt,jo({...U},Z.height||300,Ue,Bt)).overflow||At>=Ne)return{width:Ae,height:At};dt+=.03}return{width:Ae,height:Math.min(dt,Ne)}},[$,Z,se,S,N]),ze=w.useCallback(U=>{const Ce=Lp(U,.1+Math.random()*.3,.1+Math.random()*.3),Ae={...Ce,...De(Ce)};re(Ne=>[...Ne,Ae]),H(Ae.id)},[De]),Fe=w.useCallback(U=>{const Ae={...Lp(U.type,.1+Math.random()*.3,.1+Math.random()*.3),text:U.text,...U.type==="speech"&&U.speaker?{speaker:U.speaker}:{}},Ne={...Ae,...De(Ae)};re(Ge=>[...Ge,Ne]),H(Ne.id)},[De]),we=w.useCallback((U,Ce)=>{re(Ae=>Ae.map(Ne=>Ne.id===U?{...Ne,...Ce}:Ne))},[]),He=w.useCallback(U=>{var dt;const Ce=Z.height||300,Ae=Z.width>0?Nn(U.width,Z.width):200,Ne=Z.height>0?Nn(U.height,Z.height):100,Ge=U.type==="sfx"?N:S,Ue=No(se(Ge),U.text,Ae,Ne,jo({...U,textStyle:void 0},Ce,Ae,Ne));we(U.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,Ce),fontWeight:((dt=U.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,se,we]),tt=w.useCallback(U=>{re(Ce=>Ce.filter(Ae=>Ae.id!==U)),H(null),z(!1)},[]),st=w.useCallback(()=>{H(null),z(!1)},[]),it=w.useCallback((U,Ce)=>{U.stopPropagation(),H(Ce),z(!1)},[]),Nt=w.useCallback((U,Ce,Ae)=>{U.stopPropagation(),U.preventDefault();const Ne=R.find(Ge=>Ge.id===Ce);Ne&&(H(Ce),he.current={id:Ce,mode:Ae,startX:U.clientX,startY:U.clientY,origX:Ne.x,origY:Ne.y,origW:Ne.width,origH:Ne.height})},[R]);w.useEffect(()=>{const U=Ae=>{const Ne=he.current;if(!Ne||Z.width===0)return;const Ge=dy(Ae.clientX-Ne.startX,Z.width),Ue=dy(Ae.clientY-Ne.startY,Z.height);if(Ne.mode==="move"){const dt=pu(Ne.origX+Ge,0,1-Ne.origW),_t=pu(Ne.origY+Ue,0,1-Ne.origH);we(Ne.id,{x:dt,y:_t})}else{const dt=pu(Ne.origW+Ge,py,1-Ne.origX),_t=pu(Ne.origH+Ue,py,1-Ne.origY);we(Ne.id,{width:dt,height:_t})}},Ce=()=>{he.current=null};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",Ce),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Ce)}},[Z,we]);const Be=w.useCallback(async()=>{var U;C(null);try{const Ce=al(R),Ae=((U=t.aiDraft)==null?void 0:U.status)==="generated"&&Ce!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ae??null),f&&a()}catch(Ce){C(Ce instanceof Error?Ce.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(O>0&&!I){const U=O;D(`${U} overlay${U===1?"":"s"} from the cut plan ${U===1?"has":"have"} no usable position and cannot be exported — re-place ${U===1?"it":"them"} or discard ${U===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:U,ensureFontsReady:Ce}=await uy(async()=>{const{exportCut:Yt,ensureFontsReady:an}=await import("./export-cut-33MiJugN.js");return{exportCut:Yt,ensureFontsReady:an}},[]),Ae=R.some(Yt=>Yt.type==="sfx"),Ne=[b.family,...Ae?[v.family]:[]],{ready:Ge,missing:Ue}=await Ce(Ne);if(!Ge){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const dt=M.url,_t=await U(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=_t.type==="image/webp"?"webp":"jpg";At.append("file",_t,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)ye(al(R)),o==null||o();else{const Yt=await Ut.json();D(Yt.error||"Export failed")}}catch(U){D(U instanceof Error?U.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,O,I]),Te=R.find(U=>U.id===V),qt=w.useMemo(()=>X3(R),[R]),yi=w.useRef(t.id);w.useEffect(()=>{yi.current!==t.id&&(yi.current=t.id,ye(al(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:ue,current:R}),Je=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),ee=w.useMemo(()=>km(t),[t]),be=w.useMemo(()=>{const U={};for(const Ce of R){const Ae=F3(Ce);let Ne=!1;if($&&Z.width>0&&Ce.text){const Ge=Ce.type==="sfx"?N:S,Ue=Nn(Ce.width,Z.width),dt=Nn(Ce.height,Z.height);Ne=No(se(Ge),Ce.text,Ue,dt,jo(Ce,Z.height||300,Ue,dt)).overflow}(Ae||Ne)&&(U[Ce.id]={outOfBounds:Ae,overflow:Ne})}return U},[R,$,Z,se,S,N]),Me=Object.keys(be).length,$e=t.kind==="text",Xe=!t.cleanImagePath;return!$e&&Xe&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:F,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:F?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Be()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),O>0&&!I?d.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:[d.jsxs("span",{children:[O," overlay",O===1?"":"s"," ","from the cut plan ",O===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",O===1?"it":"them",", or"]}),d.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 ",O," unplaceable overlay",O===1?"":"s"]})]}):O>0?d.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 ",O," unplaceable overlay",O===1?"":"s"," — the export will not include"," ",O===1?"it":"them","."]}):q?d.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,qt.length>0&&d.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,": ",qt.length," bubble"," ",qt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",qt.map(U=>`#${U.indexA+1} ${Lf(R[U.indexA])} ↔ #${U.indexB+1} ${Lf(R[U.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",Je.hasCleanImage],["script-text","Script text",Je.hasScriptText],["bubbles",`Bubbles placed${Je.bubblesPlaced?` (${Je.bubblesPlaced})`:""}`,Je.bubblesPlaced>0],["exported","Final exported",Je.exported],["uploaded","Uploaded",Je.uploaded]].map(([U,Ce,Ae])=>d.jsxs("span",{"data-testid":`lettering-check-${U}`,"data-done":Ae?"true":"false",className:`flex items-center gap-1 ${Ae?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ae?"✓":"○"}),Ce]},U))}),Ct&&d.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."}),Me>0&&d.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:[Me," bubble",Me===1?"":"s"," may not export cleanly:"," ",Object.entries(be).map(([U,Ce])=>{const Ae=R.findIndex(Ge=>Ge.id===U),Ne=[Ce.outOfBounds?"outside image":null,Ce.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ae+1} ${Lf(R[Ae])} (${Ne})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:st,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:U=>{if(U&&Z.width===0){const Ce=U.getBoundingClientRect();Ce.width>0&&ae({x:0,y:0,width:Ce.width,height:Ce.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(U=>{if(U.type!=="speech")return null;const Ce=Z.x+Nn(U.x,Z.width),Ae=Z.y+Nn(U.y,Z.height),Ne=Nn(U.width,Z.width),Ge=Nn(U.height,Z.height),Ue=$S(U,Ne,Ge),dt=U.tailAnchor?ym(Ce,Ae,Ne,Ge,U.tailAnchor,Ue):null,_t=Math.max(1.5,Z.height*.004),At=U.id===V;return d.jsx("path",{"data-testid":`balloon-${U.id}`,d:qS(Ce,Ae,Ne,Ge,dt,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?_t+.5:_t,strokeLinejoin:"round"},U.id)})}),Z.width>0&&R.map(U=>{const Ce=Z.x+Nn(U.x,Z.width),Ae=Z.y+Nn(U.y,Z.height),Ne=Nn(U.width,Z.width),Ge=Nn(U.height,Z.height),Ue=U.id===V,dt=U.type==="speech",_t=U.type==="narration",At=!!be[U.id];return d.jsxs("div",{"data-testid":`overlay-${U.id}`,"data-warning":At?"true":"false",onClick:Bt=>it(Bt,U.id),onMouseDown:Bt=>Nt(Bt,U.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[U.type]}`} ${_t?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!dt?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:Ce,top:Ae,width:Ne,height:Ge},children:[(()=>{var an,ai;const Bt=U.type==="sfx"?N:S;if(!U.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[U.type]});const Ut=U.type!=="sfx"&&!!U.speaker;if(!$)return d.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(Ge*.05,16)),fontWeight:((an=U.textStyle)==null?void 0:an.fontWeight)??400},"data-testid":`overlay-text-${U.id}`,"data-fonts-ready":"false",children:Ut?`${U.speaker}: ${U.text}`:U.text});const Yt=No(se(Bt),U.text,Ne,Ge,jo(U,Z.height,Ne,Ge));return d.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-${U.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Yt.speakerFontSize,lineHeight:1.2},children:U.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Yt.fontSize,lineHeight:`${Yt.lineHeight}px`,fontWeight:((ai=U.textStyle)==null?void 0:ai.fontWeight)??400},children:Yt.lines.map((An,Rn)=>d.jsx("span",{className:"block",children:An},Rn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),Nt(Bt,U.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${U.id}`})]},U.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((pi=t.aiDraft)==null?void 0:pi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),ee.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:ee.map(U=>d.jsxs("button",{onClick:()=>Fe(U),"data-testid":`script-insert-${U.key}`,title:`Add ${U.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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[U.type]]})," ",d.jsxs("span",{className:"text-muted",children:[U.speaker?`${U.speaker}: `:"",U.text.length>32?`${U.text.slice(0,32)}…`:U.text]})]},U.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:U=>we(Te.id,{speaker:U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:U=>we(Te.id,{text:U.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"})]}),d.jsx("button",{onClick:()=>we(Te.id,De(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=Te.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>we(Te.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"}):d.jsx("button",{type:"button",onClick:()=>He(Te),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"})]}),((St=Te.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontWeight:U.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(U.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(U.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const U=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Ce=>d.jsx("button",{type:"button",onClick:()=>we(Te.id,{tailAnchor:Ce.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-${Ce.key}`,children:Ce.label},Ce.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:U.x,onChange:Ce=>we(Te.id,{tailAnchor:{...U,x:parseFloat(Ce.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:U.y,onChange:Ce=>we(Te.id,{tailAnchor:{...U,y:parseFloat(Ce.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Gt=Te.bubbleStyle)==null?void 0:Gt.paddingX)??.06)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((ot=Te.bubbleStyle)==null?void 0:ot.paddingY)??.08)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Ht=Te.bubbleStyle)==null?void 0:Ht.cornerRadius)??.4)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(U.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?tt(Te.id):z(!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:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[O,I]=w.useState(!1),[A,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,re]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var se;try{(se=document.fonts)!=null&&se.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const se=new ResizeObserver(()=>{re({width:B.clientWidth,height:B.clientHeight})});return se.observe(B),()=>se.disconnect()},[]);const ue=w.useCallback(B=>(se,$,G=400)=>E?(E.font=`${G} ${$}px ${B}`,E.measureText(se).width):se.length*$*.5,[E]),ye=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const se=B.currentTarget.naturalWidth||A.width,$=B.currentTarget.naturalHeight||A.height;se>0&&$>0&&q({width:se,height:$})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const se=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=$S(B,G,V),T=B.tailAnchor?ym(se,$,G,V,B.tailAnchor,H):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(se,$,G,V,T,H),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var F;const se=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:se,top:$,width:G,height:V},children:B.text?O?(()=>{var j;const xe=No(ue(H),B.text,G,V,jo(B,R.height,G,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:H},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:H,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((F=B.textStyle)==null?void 0:F.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:H},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:ye}):ye}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` +`,...o.current()});return/^[\t ]/.test(f)&&(f=Ho(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(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 f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(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))}yS.peek=yR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(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 f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(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 f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),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"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function xm(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 wR(e){const t=xm(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 CR(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 wS(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 kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):xm(i);const h=e.ordered?c==="."?")":".":wR(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),wS(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"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(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 f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(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 LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Df,tableHeader:Df,tableRow:Df}}}function zR(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 PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(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,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),L=f([E]);return L.slice(0,L.indexOf(` +`))}function p(v,S,N,M){const E=N.enter("tableCell"),L=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return L(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const L=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(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 f=xr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(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 u3(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",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(xr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=xr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Yo,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(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 m3(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=pl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(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 x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[re][1].type;if(V==="lineEnding"||V==="linePrefix")re--;else break}const $=re>-1?s.events[re][1].type:null,G=$==="tableHead"||$==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):mt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,mt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return mt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?A(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),L(B)):q(B)}function L(B){return B===45?(e.consume(B),L):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return mt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ne(B)}function ne(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ne):B===null||Ye(B)?(e.exit("tableRow"),t(B)):mt(B)?yt(e,ne,"whitespace")(B):(e.enter("data"),ue(B))}function ue(B){return B===null||B===124||qt(B)?(e.exit("data"),ne(B)):(e.consume(B),B===92?ye:ue)}function ye(B){return B===92||B===124?(e.consume(B),ue):ue(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ll(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=ll(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 ll(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(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 Ye(p)?t(p):mt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ml={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["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"]},Is={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ml,...t}:ml,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(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 Ko(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Ko(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(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&&Is.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 f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const hl=["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"],rs=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(hl.map(e=>[IS(e),e])),P3={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 Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(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(HS(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 ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(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 jo(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),f=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 M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,L=Math.max(1,_-E),I=a.fontWeight??400,A=iy((ne,ue)=>e(ne,ue,I),t,f,N),q=A.length*N*o,R=A.every(ne=>e(ne,N,I)<=f+.5);return{lines:A,ok:q<=L&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function dl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=dl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=dl(t.lineHeightFactor,.9,2),c=dl(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 Vu(e){if(!e||typeof e!="object")return;const t=e,i=dl(t.paddingX,0,.25),s=dl(t.paddingY,0,.25),a=dl(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 To(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(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 $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(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?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:L,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:L-I,y:E},base2:{x:L+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!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 f&&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 qS(e,t,i,s,a,o){const c=$3(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 F3(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 ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,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 WS(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 du=.05;function Ki(e){return typeof e=="number"&&Number.isFinite(e)}function q3(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 f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ki(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ki(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ki(t.x)&&Ki(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Ki(b.x)&&Ki(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Ki(t.x)&&Ki(t.y)&&Ki(t.width)&&Ki(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(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),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function r4(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=vm(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=Vu(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 sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Ki(e==null?void 0:e.x)&&Ki(e==null?void 0:e.y)&&Ki(e==null?void 0:e.width)&&Ki(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({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 d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.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:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.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:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.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."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(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 nD=[/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 rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(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=rD(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 XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(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 Mf=[{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 aD(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,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.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=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.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:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(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)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.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."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.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 oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={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 So(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(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.total,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(L=>!_[L]),v=L=>s.needClean>0?So(L,s.needClean):"no image cuts",S={plan:So(s.total,s.total),clean:v(s.withClean),letter:So(s.withText,s.total),export:So(s.exported,s.total),upload:So(s.uploaded,s.total),publish:null},N=x.map((L,I)=>({key:L,label:cD[L],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.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:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.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"}),d.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"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.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:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.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."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.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 xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.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(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}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)})},Cm=[{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:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(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 cl(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 wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==cl(e.current)}function km(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 CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function An(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{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 pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Gt,pi,Rt,St,Yt,ot,Ht;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let U=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Ce}=await uy(async()=>{const{ensureFontsReady:Ae}=await import("./export-cut-BeffiHI_.js");return{ensureFontsReady:Ae}},[]);await Ce([b.family,v.family])}catch{}U||G(!0)})(),()=>{U=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),L=E.invalid.length,[I,A]=w.useState(!1),q=L===0&&E.changed&&E.overlays.length>0,[R,ne]=w.useState(()=>E.overlays),[ue,ye]=w.useState(()=>cl(E.overlays)),B=w.useRef(null),re=w.useCallback(U=>(Ce,Ae,Ne=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ge?(Ge.font=`${Ne} ${Ae}px ${U}`,Ge.measureText(Ce).width):Ce.length*Ae*.5},[]),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(!1),[F,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),he=w.useRef(null),ge=w.useCallback(()=>{const U=oe.current;if(!U)return;const Ce=U.clientWidth,Ae=U.clientHeight;let Ne,Ge;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ne=At.width,Ge=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ne=At.naturalWidth,Ge=At.naturalHeight}if(!Ce||!Ae)return;const Ue=Math.min(Ce/Ne,Ae/Ge),dt=Ne*Ue,_t=Ge*Ue;ae({x:(Ce-dt)/2,y:(Ae-_t)/2,width:dt,height:_t})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const U=oe.current;if(!U)return;const Ce=new ResizeObserver(()=>ge());return Ce.observe(U),()=>Ce.disconnect()},[ge]);const De=w.useCallback(U=>{const Ce=WS(U.type,U.x,U.y),Ae=Ce.width,Ne=Math.max(.08,1-U.y);if(!U.text||!$||Z.width<=0)return Ce;const Ge=U.type==="sfx"?N:S,Ue=An(Ae,Z.width);let dt=U.type==="sfx"?.08:.12;for(let _t=0;_t<24;_t++){const At=Math.min(dt,Ne),Bt=An(At,Z.height);if(!jo(re(Ge),U.text,Ue,Bt,To({...U},Z.height||300,Ue,Bt)).overflow||At>=Ne)return{width:Ae,height:At};dt+=.03}return{width:Ae,height:Math.min(dt,Ne)}},[$,Z,re,S,N]),ze=w.useCallback(U=>{const Ce=Lp(U,.1+Math.random()*.3,.1+Math.random()*.3),Ae={...Ce,...De(Ce)};ne(Ne=>[...Ne,Ae]),H(Ae.id)},[De]),Fe=w.useCallback(U=>{const Ae={...Lp(U.type,.1+Math.random()*.3,.1+Math.random()*.3),text:U.text,...U.type==="speech"&&U.speaker?{speaker:U.speaker}:{}},Ne={...Ae,...De(Ae)};ne(Ge=>[...Ge,Ne]),H(Ne.id)},[De]),we=w.useCallback((U,Ce)=>{ne(Ae=>Ae.map(Ne=>Ne.id===U?{...Ne,...Ce}:Ne))},[]),He=w.useCallback(U=>{var dt;const Ce=Z.height||300,Ae=Z.width>0?An(U.width,Z.width):200,Ne=Z.height>0?An(U.height,Z.height):100,Ge=U.type==="sfx"?N:S,Ue=jo(re(Ge),U.text,Ae,Ne,To({...U,textStyle:void 0},Ce,Ae,Ne));we(U.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,Ce),fontWeight:((dt=U.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,re,we]),it=w.useCallback(U=>{ne(Ce=>Ce.filter(Ae=>Ae.id!==U)),H(null),z(!1)},[]),st=w.useCallback(()=>{H(null),z(!1)},[]),nt=w.useCallback((U,Ce)=>{U.stopPropagation(),H(Ce),z(!1)},[]),Nt=w.useCallback((U,Ce,Ae)=>{U.stopPropagation(),U.preventDefault();const Ne=R.find(Ge=>Ge.id===Ce);Ne&&(H(Ce),he.current={id:Ce,mode:Ae,startX:U.clientX,startY:U.clientY,origX:Ne.x,origY:Ne.y,origW:Ne.width,origH:Ne.height})},[R]);w.useEffect(()=>{const U=Ae=>{const Ne=he.current;if(!Ne||Z.width===0)return;const Ge=dy(Ae.clientX-Ne.startX,Z.width),Ue=dy(Ae.clientY-Ne.startY,Z.height);if(Ne.mode==="move"){const dt=pu(Ne.origX+Ge,0,1-Ne.origW),_t=pu(Ne.origY+Ue,0,1-Ne.origH);we(Ne.id,{x:dt,y:_t})}else{const dt=pu(Ne.origW+Ge,py,1-Ne.origX),_t=pu(Ne.origH+Ue,py,1-Ne.origY);we(Ne.id,{width:dt,height:_t})}},Ce=()=>{he.current=null};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",Ce),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Ce)}},[Z,we]);const Be=w.useCallback(async()=>{var U;C(null);try{const Ce=cl(R),Ae=((U=t.aiDraft)==null?void 0:U.status)==="generated"&&Ce!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ae??null),f&&a()}catch(Ce){C(Ce instanceof Error?Ce.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(L>0&&!I){const U=L;D(`${U} overlay${U===1?"":"s"} from the cut plan ${U===1?"has":"have"} no usable position and cannot be exported — re-place ${U===1?"it":"them"} or discard ${U===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:U,ensureFontsReady:Ce}=await uy(async()=>{const{exportCut:Vt,ensureFontsReady:an}=await import("./export-cut-BeffiHI_.js");return{exportCut:Vt,ensureFontsReady:an}},[]),Ae=R.some(Vt=>Vt.type==="sfx"),Ne=[b.family,...Ae?[v.family]:[]],{ready:Ge,missing:Ue}=await Ce(Ne);if(!Ge){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const dt=M.url,_t=await U(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=_t.type==="image/webp"?"webp":"jpg";At.append("file",_t,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)ye(cl(R)),o==null||o();else{const Vt=await Ut.json();D(Vt.error||"Export failed")}}catch(U){D(U instanceof Error?U.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,L,I]),Te=R.find(U=>U.id===V),Wt=w.useMemo(()=>X3(R),[R]),vi=w.useRef(t.id);w.useEffect(()=>{vi.current!==t.id&&(vi.current=t.id,ye(cl(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:ue,current:R}),et=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),ee=w.useMemo(()=>km(t),[t]),be=w.useMemo(()=>{const U={};for(const Ce of R){const Ae=F3(Ce);let Ne=!1;if($&&Z.width>0&&Ce.text){const Ge=Ce.type==="sfx"?N:S,Ue=An(Ce.width,Z.width),dt=An(Ce.height,Z.height);Ne=jo(re(Ge),Ce.text,Ue,dt,To(Ce,Z.height||300,Ue,dt)).overflow}(Ae||Ne)&&(U[Ce.id]={outOfBounds:Ae,overflow:Ne})}return U},[R,$,Z,re,S,N]),Me=Object.keys(be).length,$e=t.kind==="text",Xe=!t.cleanImagePath;return!$e&&Xe&&R.length===0&&!t.narration&&!((Gt=t.dialogue)!=null&&Gt.length)?d.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."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"}),d.jsx("button",{onClick:()=>ze("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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:F,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:F?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Be()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),L>0&&!I?d.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:[d.jsxs("span",{children:[L," overlay",L===1?"":"s"," ","from the cut plan ",L===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",L===1?"it":"them",", or"]}),d.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 ",L," unplaceable overlay",L===1?"":"s"]})]}):L>0?d.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 ",L," unplaceable overlay",L===1?"":"s"," — the export will not include"," ",L===1?"it":"them","."]}):q?d.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,Wt.length>0&&d.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,": ",Wt.length," bubble"," ",Wt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Wt.map(U=>`#${U.indexA+1} ${Lf(R[U.indexA])} ↔ #${U.indexB+1} ${Lf(R[U.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.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",et.hasCleanImage],["script-text","Script text",et.hasScriptText],["bubbles",`Bubbles placed${et.bubblesPlaced?` (${et.bubblesPlaced})`:""}`,et.bubblesPlaced>0],["exported","Final exported",et.exported],["uploaded","Uploaded",et.uploaded]].map(([U,Ce,Ae])=>d.jsxs("span",{"data-testid":`lettering-check-${U}`,"data-done":Ae?"true":"false",className:`flex items-center gap-1 ${Ae?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ae?"✓":"○"}),Ce]},U))}),Ct&&d.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."}),Me>0&&d.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:[Me," bubble",Me===1?"":"s"," may not export cleanly:"," ",Object.entries(be).map(([U,Ce])=>{const Ae=R.findIndex(Ge=>Ge.id===U),Ne=[Ce.outOfBounds?"outside image":null,Ce.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ae+1} ${Lf(R[Ae])} (${Ne})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:st,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.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&&!M.url?d.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?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:U=>{if(U&&Z.width===0){const Ce=U.getBoundingClientRect();Ce.width>0&&ae({x:0,y:0,width:Ce.width,height:Ce.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(U=>{if(U.type!=="speech")return null;const Ce=Z.x+An(U.x,Z.width),Ae=Z.y+An(U.y,Z.height),Ne=An(U.width,Z.width),Ge=An(U.height,Z.height),Ue=$S(U,Ne,Ge),dt=U.tailAnchor?ym(Ce,Ae,Ne,Ge,U.tailAnchor,Ue):null,_t=Math.max(1.5,Z.height*.004),At=U.id===V;return d.jsx("path",{"data-testid":`balloon-${U.id}`,d:qS(Ce,Ae,Ne,Ge,dt,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?_t+.5:_t,strokeLinejoin:"round"},U.id)})}),Z.width>0&&R.map(U=>{const Ce=Z.x+An(U.x,Z.width),Ae=Z.y+An(U.y,Z.height),Ne=An(U.width,Z.width),Ge=An(U.height,Z.height),Ue=U.id===V,dt=U.type==="speech",_t=U.type==="narration",At=!!be[U.id];return d.jsxs("div",{"data-testid":`overlay-${U.id}`,"data-warning":At?"true":"false",onClick:Bt=>nt(Bt,U.id),onMouseDown:Bt=>Nt(Bt,U.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[U.type]}`} ${_t?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!dt?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:Ce,top:Ae,width:Ne,height:Ge},children:[(()=>{var an,ri;const Bt=U.type==="sfx"?N:S;if(!U.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[U.type]});const Ut=U.type!=="sfx"&&!!U.speaker;if(!$)return d.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(Ge*.05,16)),fontWeight:((an=U.textStyle)==null?void 0:an.fontWeight)??400},"data-testid":`overlay-text-${U.id}`,"data-fonts-ready":"false",children:Ut?`${U.speaker}: ${U.text}`:U.text});const Vt=jo(re(Bt),U.text,Ne,Ge,To(U,Z.height,Ne,Ge));return d.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-${U.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Vt.speakerFontSize,lineHeight:1.2},children:U.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Vt.fontSize,lineHeight:`${Vt.lineHeight}px`,fontWeight:((ri=U.textStyle)==null?void 0:ri.fontWeight)??400},children:Vt.lines.map((Mn,Bn)=>d.jsx("span",{className:"block",children:Mn},Bn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),Nt(Bt,U.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${U.id}`})]},U.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((pi=t.aiDraft)==null?void 0:pi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),ee.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:ee.map(U=>d.jsxs("button",{onClick:()=>Fe(U),"data-testid":`script-insert-${U.key}`,title:`Add ${U.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:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[U.type]]})," ",d.jsxs("span",{className:"text-muted",children:[U.speaker?`${U.speaker}: `:"",U.text.length>32?`${U.text.slice(0,32)}…`:U.text]})]},U.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:U=>we(Te.id,{speaker:U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:U=>we(Te.id,{text:U.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"})]}),d.jsx("button",{onClick:()=>we(Te.id,De(Te)),"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"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=Te.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>we(Te.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"}):d.jsx("button",{type:"button",onClick:()=>He(Te),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"})]}),((St=Te.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontWeight:U.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:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(U.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"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(U.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"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const U=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Ce=>d.jsx("button",{type:"button",onClick:()=>we(Te.id,{tailAnchor:Ce.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-${Ce.key}`,children:Ce.label},Ce.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:U.x,onChange:Ce=>we(Te.id,{tailAnchor:{...U,x:parseFloat(Ce.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"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:U.y,onChange:Ce=>we(Te.id,{tailAnchor:{...U,y:parseFloat(Ce.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"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Yt=Te.bubbleStyle)==null?void 0:Yt.paddingX)??.06)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((ot=Te.bubbleStyle)==null?void 0:ot.paddingY)??.08)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(U.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Ht=Te.bubbleStyle)==null?void 0:Ht.cornerRadius)??.4)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(U.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"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?it(Te.id):z(!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:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[L,I]=w.useState(!1),[A,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,ne]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var re;try{(re=document.fonts)!=null&&re.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const re=new ResizeObserver(()=>{ne({width:B.clientWidth,height:B.clientHeight})});return re.observe(B),()=>re.disconnect()},[]);const ue=w.useCallback(B=>(re,$,G=400)=>E?(E.font=`${G} ${$}px ${B}`,E.measureText(re).width):re.length*$*.5,[E]),ye=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const re=B.currentTarget.naturalWidth||A.width,$=B.currentTarget.naturalHeight||A.height;re>0&&$>0&&q({width:re,height:$})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const re=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=$S(B,G,V),T=B.tailAnchor?ym(re,$,G,V,B.tailAnchor,H):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(re,$,G,V,T,H),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var F;const re=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:re,top:$,width:G,height:V},children:B.text?L?(()=>{var j;const xe=jo(ue(H),B.text,G,V,To(B,R.height,G,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:H},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:H,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((F=B.textStyle)==null?void 0:F.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:H},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:ye}):ye}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="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 DD(e){var a;const t=TD[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(RD),s.push(AD),s.join(` `).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(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(` -`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(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 Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const O=await GD(e);E||o(O)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const O=await YD(e,E);await i(O)}catch(O){h(O instanceof Error?O.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(O=>O.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(O=>O.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(O=>O.status!=="done").length,M=p.reduce((O,I)=>O+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(O=>d.jsxs("li",{"data-testid":`finish-step-${O.key}`,"data-status":O.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${O.status==="current"?"border-accent/40 bg-accent/10 text-accent":O.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[O.status]}),d.jsx("span",{children:O.label}),O.detail&&d.jsxs("span",{className:"text-muted",children:["· ",O.detail]})]},O.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(O=>d.jsxs("div",{"data-testid":`finish-issue-group-${O.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:O.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:O.lines.map((I,A)=>d.jsx("li",{children:I},A))})]},O.key))})]})]})]})}function tM(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 Mo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:al(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:gn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Mo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:O,converting:I,rowRef:A}){var Fe,we;const q=w.useRef(null),[R,re]=w.useState(!1),[ue,ye]=w.useState(null),[B,se]=w.useState(!1),[$,G]=w.useState(!1),[V,H]=w.useState(!1),[T,z]=w.useState(!1),F=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await O(e.id,E),z(!1),h())},[E,O,e.id,h]),X=w.useCallback(async He=>{re(!0),ye(null);try{let tt=He;if(!n1(He))try{tt=await Ku(He)}catch(Be){return ye(Be instanceof Error?Be.message:"Could not import image"),!1}const st=tt.type==="image/jpeg"?"jpg":"webp",it=new FormData;it.append("file",new File([tt],`clean.${st}`,{type:tt.type}));const Nt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:it});if(!Nt.ok){const Be=await Nt.json();return ye(Be.error||"Upload failed"),!1}return h(),!0}catch{return ye("Upload failed"),!1}finally{re(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Mo(e),he=(((we=e.overlays)==null?void 0:we.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,De=rM(e),ze=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:ze?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[De.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:De.label}),d.jsxs("span",{className:"text-muted",children:[" · ",De.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||I),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:T||I,"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:T?"Converting…":"Convert image"})]}),xe&&!j&&d.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:[S.map((He,tt)=>d.jsx("p",{className:"text-[11px] text-error",children:He},tt)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),se(!0),setTimeout(()=>se(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var st;const tt=(st=He.target.files)==null?void 0:st[0];tt&&X(tt),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=q.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>H(He=>!He),disabled:R,"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:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&H(!1)},onClose:()=>H(!1)}),!e.cleanImagePath&&d.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."}),F==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!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:$?"Copied!":"Copy Codex task"})]}),F==="missing"&&f&&d.jsx("button",{onClick:_,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"}),ue&&d.jsx("p",{className:"text-xs text-error mt-1",children:ue})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,tt)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},tt))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var mr,mi,Qt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,O]=w.useState(null),[I,A]=w.useState(null),[q,R]=w.useState(null),[re,ue]=w.useState(!1),[ye,B]=w.useState([]),[se,$]=w.useState(!1),[G,V]=w.useState(""),[H,T]=w.useState({markdownReady:!1,published:!1}),[z,F]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,he]=w.useState(null),[ge,De]=w.useState(!1),[ze,Fe]=w.useState(new Set),[we,He]=w.useState(new Map),[tt,st]=w.useState(!1),[it,Nt]=w.useState(null),[Be,ct]=w.useState(!1),[Te,qt]=w.useState(null),yi=w.useRef(new Map),Ct=w.useRef(null),Je=t.replace(/\.md$/,"");w.useEffect(()=>{var te;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),qt(c.cutId)),(te=S.current)==null||te.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ve;if(Te==null)return;const te=yi.current.get(Te);te&&((ve=te.scrollIntoView)==null||ve.call(te,{behavior:"smooth",block:"center"}),qt(null))},[Te,x]);const ee=w.useCallback(async()=>{var te;try{const ve=await i(`/api/stories/${e}/cuts/${Je}`);if(ve.status===404){b(null);return}if(!ve.ok){const me=await ve.json();O(me.error||"Failed to load cuts");return}const Y=await ve.json();b(Y),O(null);try{const me=await i(`/api/stories/${e}/${t}`);if(me.ok){const _e=await me.json(),Oe=typeof(_e==null?void 0:_e.content)=="string"?_e.content:"",Pe=Array.isArray(Y==null?void 0:Y.cuts)?Y.cuts:[],qe=Oe.length>0&&KS(Oe,Pe).ready,wt=(_e==null?void 0:_e.status)==="published"||(_e==null?void 0:_e.status)==="published-not-indexed";T({markdownReady:qe,published:wt})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(te=v.current)==null||te.call(v)}catch{O("Failed to load cuts")}finally{M(!1)}},[i,e,Je,t]),be=w.useCallback(async te=>!!(await i(`/api/stories/${e}/cuts/${Je}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)})).ok,[i,e,Je]),Me=w.useCallback(async()=>{st(!1);try{const te=await i(`/api/stories/${e}/cuts/${Je}/detect-clean-images`);if(!te.ok)return;const ve=await te.json();Fe(new Set(Array.isArray(ve.detected)?ve.detected:[]));const Y=new Map,me=ve.stale;if(Array.isArray(me))for(const _e of me){if(typeof(_e==null?void 0:_e.cutId)!="number"||typeof(_e==null?void 0:_e.message)!="string")continue;const Oe=Y.get(_e.cutId)??[];Oe.push(_e.message),Y.set(_e.cutId,Oe)}He(Y),st(!0)}catch{}},[i,e,Je]),$e=w.useCallback(async()=>{Nt(null);try{const te=await i(`/api/stories/${e}/cuts/${Je}/asset-diagnostics`);if(!te.ok)return;const ve=await te.json();Nt(Array.isArray(ve.diagnostics)?ve.diagnostics:null)}catch{}},[i,e,Je]),Xe=w.useCallback(async()=>{ct(!0);try{await Promise.all([ee(),Me(),$e()])}finally{ct(!1)}},[ee,Me,$e]),Wt=w.useCallback(async(te,ve={})=>{var _e;if(!x)return!1;const Y=x.cuts.find(Oe=>Oe.id===te);if(!Y||!Mo(Y)||(((_e=Y.overlays)==null?void 0:_e.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const me=hy(Y);if(me.length===0)return oe(`Cut ${Y.id}: no script lines available to draft.`),!1;he(te),oe(null);try{const Oe={...x,cuts:x.cuts.map(qe=>qe.id===te?{...qe,overlays:me,aiDraft:_y(me)}:qe)};return await be(Oe)?(oe(`Cut ${Y.id}: AI draft ready`),await ee(),ve.openEditor&&R(te),!0):(oe(`Cut ${Y.id}: AI draft failed`),!1)}finally{he(null)}},[x,be,ee]),pi=w.useCallback(async()=>{if(!x)return;const te=x.cuts.filter(ve=>{var Y;return Mo(ve)&&(((Y=ve.overlays)==null?void 0:Y.length)??0)===0&&!ve.finalImagePath&&!ve.uploadedCid&&!ve.uploadedUrl});if(te.length===0){oe("No unlettered cuts need an AI draft");return}De(!0),oe(null);try{const ve={...x,cuts:x.cuts.map(me=>{if(!te.some(Oe=>Oe.id===me.id))return me;const _e=hy(me);return _e.length>0?{...me,overlays:_e,aiDraft:_y(_e)}:me})};if(!await be(ve)){oe("AI draft failed");return}oe(`AI draft ready for ${te.length} cut${te.length===1?"":"s"}`),await ee()}finally{De(!1)}},[x,be,ee]),Rt=w.useCallback(async()=>{F(!0),oe(null),B([]);try{const te=await i(`/api/stories/${e}/cuts/${Je}/sync-clean-images`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Sync failed");else{const Y=Array.isArray(ve.synced)?ve.synced.length:0,me=Array.isArray(ve.cleared)?ve.cleared.length:0,_e=Array.isArray(ve.rejected)?ve.rejected:[];_e.length>0&&B(_e.map(Pe=>`Cut ${Pe.cutId}: ${Pe.reason}`));const Oe=[];Y>0&&Oe.push(`Synced ${Y}`),me>0&&Oe.push(`Cleared ${me} stale path${me===1?"":"s"}`),oe(Oe.length>0?Oe.join(", "):"No new clean images"),await ee(),await Me(),await $e()}}catch{oe("Sync failed")}F(!1)},[i,e,Je,ee,Me,$e]),St=w.useCallback(async(te,ve)=>{try{const Y=await i(HS(e,ve));if(!Y.ok)return!1;const me=await Y.blob(),_e=await Ku(new File([me],"clean.png",{type:me.type||"image/png"})),Oe=_e.type==="image/jpeg"?"jpg":"webp",Pe=new FormData;return Pe.append("file",new File([_e],`clean.${Oe}`,{type:_e.type})),(await i(`/api/stories/${e}/cuts/${Je}/upload-clean/${te}`,{method:"POST",body:Pe})).ok}catch{return!1}},[i,e,Je]),Gt=w.useCallback(async te=>{X(!0),Z(null);let ve=0;const Y=[];for(const me of te)await St(me.cutId,me.pngPath)?ve++:Y.push(me.cutId);await Xe(),X(!1),Z(Y.length===0?`Converted ${ve} image${ve===1?"":"s"} to WebP`:`Converted ${ve}; ${Y.length} failed (Cut ${Y.join(", ")}) — try Convert image on each`)},[St,Xe]),ot=w.useCallback(async()=>{var _e;if(!x)return;$(!0),V(""),B([]);const te=x.cuts.filter(Oe=>Oe.finalImagePath&&!Oe.uploadedCid),ve=[],Y=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Oe})=>V(`Upload limit reached — waiting ${Math.round(Oe/1e3)}s before continuing…`)});for(let Oe=0;Oe{const Kt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Kt.ok){const{cid:Gn,url:Dn}=await Kt.json();return{ok:!0,status:Kt.status,cid:Gn,url:Dn}}const Jt=await Kt.json().catch(()=>({}));return{ok:!1,status:Kt.status,errorMessage:Jt.error}},{...a,onWaiting:({attempt:Kt,maxRetries:Jt,waitMs:Gn})=>V(`Cut ${Pe.id} rate-limited — waiting ${Math.round(Gn/1e3)}s before retry ${Kt}/${Jt}...`)});if(!Ze.ok){ve.push(`Cut ${Pe.id}: upload failed — ${Ze.errorMessage||"unknown"}`);continue}const{cid:Qe,url:Vt}=Ze;(await i(`/api/stories/${e}/cuts/${Je}/set-uploaded/${Pe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Qe,url:Vt})})).ok||ve.push(`Cut ${Pe.id}: failed to record upload`)}catch(qe){ve.push(`Cut ${Pe.id}: ${qe instanceof Error?qe.message:"failed"}`)}}if(ve.length>0){B(ve),$(!1),V(""),ee();return}V("Preparing episode for publishing…");const me=await i(`/api/stories/${e}/cuts/${Je}/generate-markdown`,{method:"POST"});if(me.ok){const Oe=await me.json();((_e=Oe.warnings)==null?void 0:_e.length)>0&&B(Oe.warnings)}$(!1),V(""),ee()},[x,i,e,Je,a,ee]),Ht=w.useCallback(async()=>{j(!0),oe(null);try{const te=await i(`/api/stories/${e}/cuts/${Je}/repair-asset-paths`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Repair failed");else{const Y=Array.isArray(ve.cleared)?ve.cleared.length:0;oe(Y>0?`Cleared ${Y} stale path${Y===1?"":"s"}`:"No stale paths to clear"),await ee(),await Me()}}catch{oe("Repair failed")}j(!1)},[i,e,Je,ee,Me]),[U,Ce]=w.useState(!1),Ae=w.useCallback(async(te,ve=!0)=>{if(x){Ce(!0);try{const Y=x.cuts.reduce((qe,wt)=>Math.max(qe,wt.id),0)+1,me={id:Y,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"},_e=[...x.cuts];_e.splice(Math.max(0,Math.min(te,_e.length)),0,me);const Oe={...x,cuts:_e},Pe=await i(`/api/stories/${e}/cuts/${Je}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Oe)});if(Pe.ok)ve?R(Y):A(Y),await ee();else{const qe=await Pe.json().catch(()=>({}));oe(qe.error||"Could not add text panel")}}catch{oe("Could not add text panel")}Ce(!1)}},[x,i,e,Je,ee]),Ne=w.useCallback(()=>Ae((x==null?void 0:x.cuts.length)??0,!0),[Ae,x]);if(w.useEffect(()=>{ee(),Me(),$e()},[ee,Me,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Je,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:ee,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(te=>te.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:Je,language:s,authFetch:i,targetLabel:gn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(te,ve)=>{const Y={...x,cuts:x.cuts.map(_e=>_e.id===q?{..._e,overlays:te,aiDraft:ve??_e.aiDraft??null}:_e)};if(!await be(Y))throw new Error("Failed to save overlays")},onExported:()=>ee(),onClose:()=>{R(null),ee()}});const Ue=x.cuts.reduce((te,ve)=>{const Y=r1(ve);return te[Y]++,te},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(te=>!gn(te)).length,_t=x.cuts.filter(te=>GS(te)).map(te=>te.id),At=uD({cuts:x.cuts,published:H.published}),Bt=((mr=At.steps.find(te=>te.key==="upload"))==null?void 0:mr.status)==="done",Ut=x.cuts.some(te=>te.finalImagePath&&!te.uploadedCid)||Bt&&!H.markdownReady,Yt=(it??[]).filter(te=>te.state==="needs-conversion"&&te.convertiblePng).map(te=>({cutId:te.cutId,pngPath:te.convertiblePng})),an=new Map(Yt.map(te=>[te.cutId,te.pngPath])),ai=(it??[]).filter(te=>te.state==="needs-conversion"&&te.issue).map(te=>te.issue),An=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mi=Je.match(/\d+/))==null?void 0:mi[0])??"0",10)+1}`,Rn=typeof x.title=="string"?x.title:null,lr=x.cuts.filter(te=>!gn(te)),Pi={cuts:x.cuts.length,artwork:lr.filter(te=>te.cleanImagePath||an.has(te.id)).length,converted:lr.filter(te=>te.cleanImagePath&&/\.(webp|jpe?g)$/i.test(te.cleanImagePath)).length,lettered:x.cuts.filter(te=>{var ve;return(((ve=te.overlays)==null?void 0:ve.length)??0)>0||!!te.finalImagePath}).length,uploaded:x.cuts.filter(te=>te.uploadedCid||te.uploadedUrl).length},vn=x.cuts.filter(te=>{var ve;return Mo(te)&&(((ve=te.overlays)==null?void 0:ve.length)??0)===0&&!te.finalImagePath&&!te.uploadedCid&&!te.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:An}),Rn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Rn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Pi.cuts," cuts · ",Pi.artwork," artwork found ·"," ",Pi.converted," converted · ",Pi.lettered," ","lettered · ",Pi.uploaded," uploaded"]})]}),vn>0&&d.jsx("button",{onClick:pi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${vn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{ue(!0),B([]);try{const te=await i(`/api/stories/${e}/cuts/${Je}/generate-markdown`,{method:"POST"});if(te.ok){const ve=await te.json();B(ve.warnings||[])}}catch{}ue(!1)},disabled:re,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:re?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ne,disabled:U,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:U?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Xe,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"}),d.jsx("button",{onClick:Rt,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"}),d.jsx("button",{onClick:ot,disabled:se||!(x!=null&&x.cuts.some(te=>te.finalImagePath&&!te.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),_t.length>0&&d.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:[_t.length===1?"Cut":"Cuts"," ",_t.join(", ")," ",_t.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",_t.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),tt&&dt>0&&Ue.missing===0&&we.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Yt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Yt.length," PNG image",Yt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Gt(Yt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ai.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ai.map((te,ve)=>d.jsx("li",{children:te},ve))})]})]}),it&&it.length>0&&(()=>{const te=tM(it),ve=it.filter(Y=>Y.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",te.uploaded," uploaded · ",te.finalReady," final ·"," ",te.cleanReady," clean · ",te.planned," planned",te.needsConversion>0?` · ${te.needsConversion} needs conversion`:"",te.missing>0?` · ${te.missing} missing`:""]}),ve.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ve.map(Y=>d.jsx("li",{children:Y.issue},Y.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:ye,onFinish:ot,finishing:se,progressText:G,canFinish:Ut,markdownReady:H.markdownReady,published:H.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((te,ve)=>{var Y;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ve,beforeLabel:ve===0?"Episode opening":`After cut ${(Y=x.cuts[ve-1])==null?void 0:Y.id}`,afterLabel:`Before cut ${te.id}`,disabled:U,onAdd:()=>Ae(ve)}),d.jsx(sM,{cut:te,storyName:e,plotFile:Je,language:s,expanded:I===te.id,onToggle:()=>A(I===te.id?null:te.id),authFetch:i,onUpdated:()=>{ee(),Me(),$e()},onOpenEditor:()=>R(te.id),detectedLocalClean:ze.has(te.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Wt(te.id,{openEditor:!0})},aiDrafting:K===te.id,staleMessages:we.get(te.id)??[],onRepairStale:Ht,repairing:xe,conversionPng:an.get(te.id)??null,onConvert:St,converting:D,rowRef:me=>{me?yi.current.set(te.id,me):yi.current.delete(te.id)}})]},te.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Qt=x.cuts[x.cuts.length-1])==null?void 0:Qt.id}`,afterLabel:"Episode ending",disabled:U,onAdd:()=>Ae(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Ho(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 dM(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 Ip(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 Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...dl,attributes:{...dl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:O=null,onWorkflowActionHandled:I}){const[A,q]=w.useState(null),[R,re]=w.useState(!1),[ue,ye]=w.useState("preview"),[B,se]=w.useState("publish"),[$,G]=w.useState("text"),[V,H]=w.useState(null),T=w.useCallback((ne,Ee)=>{ye("edit"),H(je=>({cutId:ne,openEditor:Ee,seq:((je==null?void 0:je.seq)??0)+1}))},[]),[z,F]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,he]=w.useState(""),[ge,De]=w.useState(""),[ze,Fe]=w.useState(!1),[we,He]=w.useState(null),[tt,st]=w.useState(0),[it,Nt]=w.useState(0),[Be,ct]=w.useState(null),[Te,qt]=w.useState(null),[yi,Ct]=w.useState(null),[Je,ee]=w.useState(0),be=w.useRef(null),Me=w.useRef(!1),[$e,Xe]=w.useState(!1),[Wt,pi]=w.useState(ol[0]),[Rt,St]=w.useState(rs[0]),[Gt,ot]=w.useState(!1),[Ht,U]=w.useState(null),[Ce,Ae]=w.useState(null),[Ne,Ge]=w.useState(!1),[Ue,dt]=w.useState(!1),[_t,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Yt,an]=w.useState(!1),ai=w.useRef(null),An=w.useRef(null),[Rn,lr]=w.useState(!1),[Pi,vn]=w.useState(null),[mr,mi]=w.useState(null),[Qt,te]=w.useState("unknown"),ve=w.useRef(!1),[Y,me]=w.useState(!1),[_e,Oe]=w.useState(!1),[Pe,qe]=w.useState(null),[wt,vt]=w.useState([]),[jt,Ze]=w.useState(null),Qe=w.useRef(null),Vt=w.useRef(null),Ri=w.useRef(0),Kt=w.useCallback(async()=>{if(!e||!t){q(null);return}const ne=`${e}/${t}`,Ee=Vt.current!==ne;Ee&&(Vt.current=ne);try{const je=await i(`/api/stories/${e}/${t}`);if(je.ok){const nt=await je.json();q(nt),(Ee||!Me.current)&&(F(nt.content??""),Ee&&(X(!1),Me.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{re(!0),Kt().finally(()=>re(!1))},[Kt]),w.useEffect(()=>{if(!e||!t||ue==="edit"&&D)return;const ne=setInterval(Kt,3e3);return()=>clearInterval(ne)},[e,t,Kt,ue,D]);const[Jt,Gn]=w.useState(null),Dn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Dn||!e){Gn(null);return}let ne=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{ne||Gn(Ee?Op(Ee.cuts||[]):null)}).catch(()=>{ne||Gn(null)}),()=>{ne=!0}},[Dn,e,i]);const Br=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!Br||!e||!t){He(null),st(0),Nt(0),ct(null);return}let ne=!1;const Ee=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[je,nt]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Ee}`)]);if(ne)return;if(!nt.ok){He("error"),st(0),Nt(0),ct(null);return}const Lt=await nt.json(),gi=Lt.cuts||[],vr=je.ok?(await je.json()).content??"":"",xi=XS(vr,gi);ne||(He(xi.stage),st(xi.awaitingCount),Nt(xi.totalCuts),ct(Op(gi)),Ct(typeof Lt.title=="string"?Lt.title:null))}catch{ne||(He("error"),st(0),Nt(0),ct(null))}})(),()=>{ne=!0}},[Br,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,Je]),w.useEffect(()=>{if(!e){qt(null);return}let ne=!1;return i(`/api/stories/${e}/structure.md`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{ne||qt((Ee==null?void 0:Ee.content)??null)}).catch(()=>{}),()=>{ne=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ne=Cu(p);let Ee=ne??"";if(!ne&&Te){const nt=Te.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);nt&&(Ee=Cu(nt[1].replace(/\*+/g,"").trim())??"")}he(Ee);let je=h&&rs.find(nt=>nt.toLowerCase()===h.toLowerCase())||"";if(!je&&Te){const nt=Te.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);nt&&(je=rs.find(Lt=>Lt.toLowerCase()===nt[1].replace(/\*+/g,"").trim().toLowerCase())||"")}De(je),Fe(f??!1)},[e,p,h,f,Te]);const cs=w.useCallback(ne=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Me.current=!1,q(Ee=>Ee&&{...Ee,content:z}))}catch{}j(!1)}},[e,t,i,z]),Xt=w.useCallback(async()=>{if(!e||!t)return;const ne=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ne}/generate-markdown`,{method:"POST"})).ok&&(await Kt(),ee(je=>je+1))}catch{}},[e,t,i,Kt]);w.useEffect(()=>{if(O&&O.seq!==Ri.current){switch(Ri.current=O.seq,O.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ye("edit"),G("cuts");break;case"generate-markdown":Xt();break;case"publish":ye("preview");break}I==null||I(O.seq)}},[O,x,Xt,I]);const Ii=w.useCallback(ne=>{var nt;const Ee=(nt=ne.target.files)==null?void 0:nt[0];if(!Ee)return;ve.current=!0,vn(null),mi(null);const je=Sy(Ee);if(je){U(null),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ai.current&&(ai.current.value=""),Ut(je),te("invalid");return}U(Ee),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(Ee))),Ut(null),te("selected")},[]),Di=w.useCallback(async ne=>{var je;const Ee=(je=ne.target.files)==null?void 0:je[0];if(An.current&&(An.current.value=""),!(!Ee||!e)){ve.current=!0,vn(null),lr(!0),Ut(null);try{let nt;try{nt=await Ku(Ee)}catch(dn){U(null),Ae(Ys=>(Ys&&URL.revokeObjectURL(Ys),null)),Ut(dn instanceof Error?dn.message:"Could not import image");return}const Lt=nt.type==="image/jpeg"?"jpg":"webp",gi=new File([nt],`cover.${Lt}`,{type:nt.type}),vr=new FormData;vr.append("file",gi);const xi=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:vr});if(!xi.ok){const dn=await xi.json().catch(()=>({}));Ut(dn.error||"Cover import failed");return}U(gi),Ae(dn=>(dn&&URL.revokeObjectURL(dn),URL.createObjectURL(gi))),mi(null),te("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{lr(!1)}}},[e,i]),or=w.useCallback(async ne=>{if(ne.size>1024*1024){qe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ne.type)){qe("Only WebP and JPEG images are accepted");return}Oe(!0),qe(null);try{const je=new FormData;je.append("file",ne);const nt=await i("/api/publish/upload-plot-image",{method:"POST",body:je});if(!nt.ok){const gi=await nt.json();throw new Error(gi.error||"Upload failed")}const Lt=await nt.json();vt(gi=>[...gi,{cid:Lt.cid,url:Lt.url}])}catch(je){qe(je instanceof Error?je.message:"Upload failed")}finally{Oe(!1),Qe.current&&(Qe.current.value="")}},[i]),Gs=w.useCallback(ne=>{var je;const Ee=(je=ne.target.files)==null?void 0:je[0];Ee&&or(Ee)},[or]),ei=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ge(!0),Ut(null),an(!1);try{let ne;if(Ht){const je=new FormData;je.append("file",Ht);const nt=await i("/api/publish/upload-cover",{method:"POST",body:je});if(!nt.ok){const gi=await nt.json();throw new Error(gi.error||"Cover upload failed")}ne=(await nt.json()).cid}const Ee=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...ne!==void 0&&{coverCid:ne},genre:Wt,language:Rt,isNsfw:Gt})});if(!Ee.ok){const je=await Ee.json();throw new Error(je.error||"Update failed")}an(!0),U(null),ne!==void 0&&(At(!0),Ae(je=>(je&&URL.revokeObjectURL(je),null)),te("unknown"),ai.current&&(ai.current.value="")),setTimeout(()=>an(!1),3e3)}catch(ne){Ut(ne instanceof Error?ne.message:"Update failed")}finally{Ge(!1)}}},[A==null?void 0:A.storylineId,Ht,Wt,Rt,Gt,i]);w.useEffect(()=>{Xe(!1),U(null),Ae(null),Ut(null),an(!1),dt(!1),me(!1),vt([]),qe(null),vn(null),mi(null),te("unknown"),ve.current=!1,G("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||ve.current)return;let ne=!1;return(async()=>{try{const Ee=await i(`/api/stories/${e}/cover-asset`);if(ne||!Ee.ok)return;const je=await Ee.json();if(ne)return;if(!(je!=null&&je.found)){te("none");return}if(!je.valid){mi(je.error||"Detected cover asset is invalid and was not used"),te("invalid");return}const nt=await i(`/api/stories/${e}/asset/${je.path.replace(/^assets\//,"")}`);if(ne||!nt.ok)return;const Lt=await nt.blob(),gi=new File([Lt],je.path.split("/").pop()||"cover.webp",{type:je.type});if(Sy(gi)||ne||ve.current)return;U(gi),Ae(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(gi))),vn(je.path),te("detected")}catch{}})(),()=>{ne=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;dt(!1);const ne="https://plotlink.xyz";let Ee=!1;return fetch(`${ne}/api/storyline/${A.storylineId}`).then(je=>je.ok?je.json():null).then(je=>{if(!Ee){if(!je){Ut("Could not load current story metadata");return}if(je.genre){const nt=Cu(je.genre);nt&&pi(nt)}if(je.language){const nt=rs.find(Lt=>Lt.toLowerCase()===je.language.toLowerCase());nt&&St(nt)}je.isNsfw!==void 0&&ot(!!je.isNsfw),At(!!(je.coverCid||je.coverUrl||je.cover)),dt(!0)}}).catch(()=>{Ee||Ut("Could not load current story metadata")}),()=>{Ee=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(ue!=="edit")return;const ne=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key==="s"&&(Ee.preventDefault(),gr())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[ue,gr]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const ne=new Date(A.publishedAt).getTime(),Ee=300*1e3,je=()=>{const Lt=Math.max(0,Ee-(Date.now()-ne));oe(Lt)};je();const nt=setInterval(je,1e3);return()=>clearInterval(nt)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const Mn=ae!==null&&ae<=0,Lr=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Si=(ue==="edit"?z:(A==null?void 0:A.content)??"").length,wi=t==="genesis.md",Bn=t?/^plot-\d+\.md$/.test(t):!1,Xi=c==="cartoon"&&Bn,Zi=c==="cartoon"&&wi,us=Zi||Xi,Or=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",zr=S&&us,Ko=Zi?Jt?Jt.total:null:Xi?we===null?null:it:null,Sa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Or,cutCount:Ko,cutProgress:Zi?Jt:null}),_l=(Zi||Xi)&&!Or,Pr=_l?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:Te,contentType:"cartoon",episodeTitle:yi}):null,bl=!!Pr&&Ho(Pr,t),Xo=Xi&&!Or&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:yi}),xr=Zi&&!Or?wm((A==null?void 0:A.content)??""):null,Yn=!!xr&&xr.blockers.length>0,vl="w-full max-w-[32rem] rounded-xl border px-3 py-3",yl={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ir=ne=>{if(!Zi)return null;const Ee=cM({hasSelectedCover:!!Ht,invalid:Qt==="invalid",attached:ne});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Ee.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${yl[Ee.tone]}`,children:Ee.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},_r=bl||Xo,Zo=()=>{if(!_l||!Pr)return null;const ne=wi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":bl?"true":"false","data-blocked":_r?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ne,":"]})," ",d.jsx("span",{className:_r?"text-error font-medium":"text-foreground",children:Pr})]}),bl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",wi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Xo?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Pr,"” 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]})},Sl=()=>xr?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Yn?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),xr.blockers.map((ne,Ee)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ne},`b-${Ee}`)),xr.warnings.map((ne,Ee)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ne},`w-${Ee}`))]}):null,hs=wi||Bn?1e4:null,br=!Or&&hs!==null&&Si>hs,cr=(A==null?void 0:A.content)??"",ds=Or?{count:0,warnings:[]}:yM(cr),fs=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:be,value:z,onChange:ne=>{F(ne.target.value),X(!0),Me.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!zr&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${br?"text-error font-medium":"text-muted"}`,children:[Si.toLocaleString(),hs!==null?`/${hs.toLocaleString()}`:" chars"]}),br&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Si-hs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ye("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ye("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),ue==="preview"?Xi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:we}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Xi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(ne=>ne+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Zi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>G("text"),className:`px-2 py-0.5 text-[11px] rounded ${$==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>G("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${$==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:$==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(ne=>ne+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):fs})]}):fs,!zr&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:Sa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Mn&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),Kt())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),Bn&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,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 f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(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 $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(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 Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(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 GD(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(WD):[]}async function YD(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 VD(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 KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(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 ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const L=await GD(e);E||o(L)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const L=await YD(e,E);await i(L)}catch(L){h(L instanceof Error?L.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.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&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.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."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.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:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.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&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({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=ZS(t),f=((E=e.steps.find(L=>L.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(L=>L.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}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(L=>L.status!=="done").length,M=p.reduce((L,I)=>L+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.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-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(L=>d.jsxs("li",{"data-testid":`finish-step-${L.key}`,"data-status":L.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${L.status==="current"?"border-accent/40 bg-accent/10 text-accent":L.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[L.status]}),d.jsx("span",{children:L.label}),L.detail&&d.jsxs("span",{className:"text-muted",children:["· ",L.detail]})]},L.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(L=>d.jsxs("div",{"data-testid":`finish-issue-group-${L.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:L.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:L.lines.map((I,A)=>d.jsx("li",{children:I},A))})]},L.key))})]})]})]})}function tM(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 Bo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:cl(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(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"}:gn(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 rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Bo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:L,converting:I,rowRef:A}){var Fe,we;const q=w.useRef(null),[R,ne]=w.useState(!1),[ue,ye]=w.useState(null),[B,re]=w.useState(!1),[$,G]=w.useState(!1),[V,H]=w.useState(!1),[T,z]=w.useState(!1),F=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await L(e.id,E),z(!1),h())},[E,L,e.id,h]),X=w.useCallback(async He=>{ne(!0),ye(null);try{let it=He;if(!n1(He))try{it=await Ku(He)}catch(Be){return ye(Be instanceof Error?Be.message:"Could not import image"),!1}const st=it.type==="image/jpeg"?"jpg":"webp",nt=new FormData;nt.append("file",new File([it],`clean.${st}`,{type:it.type}));const Nt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:nt});if(!Nt.ok){const Be=await Nt.json();return ye(Be.error||"Upload failed"),!1}return h(),!0}catch{return ye("Upload failed"),!1}finally{ne(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Bo(e),he=(((we=e.overlays)==null?void 0:we.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,De=rM(e),ze=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:ze?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 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:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[De.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:De.label}),d.jsxs("span",{className:"text-muted",children:[" · ",De.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"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:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||I),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"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:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.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:[d.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."}),d.jsx("button",{onClick:D,disabled:T||I,"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:T?"Converting…":"Convert image"})]}),xe&&!j&&d.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:[S.map((He,it)=>d.jsx("p",{className:"text-[11px] text-error",children:He},it)),d.jsx("button",{onClick:N,disabled:M,"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:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),re(!0),setTimeout(()=>re(!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:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var st;const it=(st=He.target.files)==null?void 0:st[0];it&&X(it),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=q.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>H(He=>!He),disabled:R,"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:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&H(!1)},onClose:()=>H(!1)}),!e.cleanImagePath&&d.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."}),F==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.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"," ",d.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”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!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:$?"Copied!":"Copy Codex task"})]}),F==="missing"&&f&&d.jsx("button",{onClick:_,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"}),ue&&d.jsx("p",{className:"text-xs text-error mt-1",children:ue})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"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&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,it)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},it))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var _r,mi,Zt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,L]=w.useState(null),[I,A]=w.useState(null),[q,R]=w.useState(null),[ne,ue]=w.useState(!1),[ye,B]=w.useState([]),[re,$]=w.useState(!1),[G,V]=w.useState(""),[H,T]=w.useState({markdownReady:!1,published:!1}),[z,F]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,he]=w.useState(null),[ge,De]=w.useState(!1),[ze,Fe]=w.useState(new Set),[we,He]=w.useState(new Map),[it,st]=w.useState(!1),[nt,Nt]=w.useState(null),[Be,ct]=w.useState(!1),[Te,Wt]=w.useState(null),vi=w.useRef(new Map),Ct=w.useRef(null),et=t.replace(/\.md$/,"");w.useEffect(()=>{var te;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),Wt(c.cutId)),(te=S.current)==null||te.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ve;if(Te==null)return;const te=vi.current.get(Te);te&&((ve=te.scrollIntoView)==null||ve.call(te,{behavior:"smooth",block:"center"}),Wt(null))},[Te,x]);const ee=w.useCallback(async()=>{var te;try{const ve=await i(`/api/stories/${e}/cuts/${et}`);if(ve.status===404){b(null);return}if(!ve.ok){const me=await ve.json();L(me.error||"Failed to load cuts");return}const Y=await ve.json();b(Y),L(null);try{const me=await i(`/api/stories/${e}/${t}`);if(me.ok){const _e=await me.json(),Oe=typeof(_e==null?void 0:_e.content)=="string"?_e.content:"",Pe=Array.isArray(Y==null?void 0:Y.cuts)?Y.cuts:[],qe=Oe.length>0&&KS(Oe,Pe).ready,wt=(_e==null?void 0:_e.status)==="published"||(_e==null?void 0:_e.status)==="published-not-indexed";T({markdownReady:qe,published:wt})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(te=v.current)==null||te.call(v)}catch{L("Failed to load cuts")}finally{M(!1)}},[i,e,et,t]),be=w.useCallback(async te=>!!(await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)})).ok,[i,e,et]),Me=w.useCallback(async()=>{st(!1);try{const te=await i(`/api/stories/${e}/cuts/${et}/detect-clean-images`);if(!te.ok)return;const ve=await te.json();Fe(new Set(Array.isArray(ve.detected)?ve.detected:[]));const Y=new Map,me=ve.stale;if(Array.isArray(me))for(const _e of me){if(typeof(_e==null?void 0:_e.cutId)!="number"||typeof(_e==null?void 0:_e.message)!="string")continue;const Oe=Y.get(_e.cutId)??[];Oe.push(_e.message),Y.set(_e.cutId,Oe)}He(Y),st(!0)}catch{}},[i,e,et]),$e=w.useCallback(async()=>{Nt(null);try{const te=await i(`/api/stories/${e}/cuts/${et}/asset-diagnostics`);if(!te.ok)return;const ve=await te.json();Nt(Array.isArray(ve.diagnostics)?ve.diagnostics:null)}catch{}},[i,e,et]),Xe=w.useCallback(async()=>{ct(!0);try{await Promise.all([ee(),Me(),$e()])}finally{ct(!1)}},[ee,Me,$e]),Gt=w.useCallback(async(te,ve={})=>{var _e;if(!x)return!1;const Y=x.cuts.find(Oe=>Oe.id===te);if(!Y||!Bo(Y)||(((_e=Y.overlays)==null?void 0:_e.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const me=hy(Y);if(me.length===0)return oe(`Cut ${Y.id}: no script lines available to draft.`),!1;he(te),oe(null);try{const Oe={...x,cuts:x.cuts.map(qe=>qe.id===te?{...qe,overlays:me,aiDraft:_y(me)}:qe)};return await be(Oe)?(oe(`Cut ${Y.id}: AI draft ready`),await ee(),ve.openEditor&&R(te),!0):(oe(`Cut ${Y.id}: AI draft failed`),!1)}finally{he(null)}},[x,be,ee]),pi=w.useCallback(async()=>{if(!x)return;const te=x.cuts.filter(ve=>{var Y;return Bo(ve)&&(((Y=ve.overlays)==null?void 0:Y.length)??0)===0&&!ve.finalImagePath&&!ve.uploadedCid&&!ve.uploadedUrl});if(te.length===0){oe("No unlettered cuts need an AI draft");return}De(!0),oe(null);try{const ve={...x,cuts:x.cuts.map(me=>{if(!te.some(Oe=>Oe.id===me.id))return me;const _e=hy(me);return _e.length>0?{...me,overlays:_e,aiDraft:_y(_e)}:me})};if(!await be(ve)){oe("AI draft failed");return}oe(`AI draft ready for ${te.length} cut${te.length===1?"":"s"}`),await ee()}finally{De(!1)}},[x,be,ee]),Rt=w.useCallback(async()=>{F(!0),oe(null),B([]);try{const te=await i(`/api/stories/${e}/cuts/${et}/sync-clean-images`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Sync failed");else{const Y=Array.isArray(ve.synced)?ve.synced.length:0,me=Array.isArray(ve.cleared)?ve.cleared.length:0,_e=Array.isArray(ve.rejected)?ve.rejected:[];_e.length>0&&B(_e.map(Pe=>`Cut ${Pe.cutId}: ${Pe.reason}`));const Oe=[];Y>0&&Oe.push(`Synced ${Y}`),me>0&&Oe.push(`Cleared ${me} stale path${me===1?"":"s"}`),oe(Oe.length>0?Oe.join(", "):"No new clean images"),await ee(),await Me(),await $e()}}catch{oe("Sync failed")}F(!1)},[i,e,et,ee,Me,$e]),St=w.useCallback(async(te,ve)=>{try{const Y=await i(HS(e,ve));if(!Y.ok)return!1;const me=await Y.blob(),_e=await Ku(new File([me],"clean.png",{type:me.type||"image/png"})),Oe=_e.type==="image/jpeg"?"jpg":"webp",Pe=new FormData;return Pe.append("file",new File([_e],`clean.${Oe}`,{type:_e.type})),(await i(`/api/stories/${e}/cuts/${et}/upload-clean/${te}`,{method:"POST",body:Pe})).ok}catch{return!1}},[i,e,et]),Yt=w.useCallback(async te=>{X(!0),Z(null);let ve=0;const Y=[];for(const me of te)await St(me.cutId,me.pngPath)?ve++:Y.push(me.cutId);await Xe(),X(!1),Z(Y.length===0?`Converted ${ve} image${ve===1?"":"s"} to WebP`:`Converted ${ve}; ${Y.length} failed (Cut ${Y.join(", ")}) — try Convert image on each`)},[St,Xe]),ot=w.useCallback(async()=>{var _e;if(!x)return;$(!0),V(""),B([]);const te=x.cuts.filter(Oe=>Oe.finalImagePath&&!Oe.uploadedCid),ve=[],Y=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Oe})=>V(`Upload limit reached — waiting ${Math.round(Oe/1e3)}s before continuing…`)});for(let Oe=0;Oe{const gi=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(gi.ok){const{cid:Di,url:yn}=await gi.json();return{ok:!0,status:gi.status,cid:Di,url:yn}}const li=await gi.json().catch(()=>({}));return{ok:!1,status:gi.status,errorMessage:li.error}},{...a,onWaiting:({attempt:gi,maxRetries:li,waitMs:Di})=>V(`Cut ${Pe.id} rate-limited — waiting ${Math.round(Di/1e3)}s before retry ${gi}/${li}...`)});if(!Ze.ok){ve.push(`Cut ${Pe.id}: upload failed — ${Ze.errorMessage||"unknown"}`);continue}const{cid:Qe,url:Kt}=Ze;(await i(`/api/stories/${e}/cuts/${et}/set-uploaded/${Pe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Qe,url:Kt})})).ok||ve.push(`Cut ${Pe.id}: failed to record upload`)}catch(qe){ve.push(`Cut ${Pe.id}: ${qe instanceof Error?qe.message:"failed"}`)}}if(ve.length>0){B(ve),$(!1),V(""),ee();return}V("Preparing episode for publishing…");const me=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(me.ok){const Oe=await me.json();((_e=Oe.warnings)==null?void 0:_e.length)>0&&B(Oe.warnings)}$(!1),V(""),ee()},[x,i,e,et,a,ee]),Ht=w.useCallback(async()=>{j(!0),oe(null);try{const te=await i(`/api/stories/${e}/cuts/${et}/repair-asset-paths`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Repair failed");else{const Y=Array.isArray(ve.cleared)?ve.cleared.length:0;oe(Y>0?`Cleared ${Y} stale path${Y===1?"":"s"}`:"No stale paths to clear"),await ee(),await Me()}}catch{oe("Repair failed")}j(!1)},[i,e,et,ee,Me]),[U,Ce]=w.useState(!1),Ae=w.useCallback(async(te,ve=!0)=>{if(x){Ce(!0);try{const Y=x.cuts.reduce((qe,wt)=>Math.max(qe,wt.id),0)+1,me={id:Y,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"},_e=[...x.cuts];_e.splice(Math.max(0,Math.min(te,_e.length)),0,me);const Oe={...x,cuts:_e},Pe=await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Oe)});if(Pe.ok)ve?R(Y):A(Y),await ee();else{const qe=await Pe.json().catch(()=>({}));oe(qe.error||"Could not add text panel")}}catch{oe("Could not add text panel")}Ce(!1)}},[x,i,e,et,ee]),Ne=w.useCallback(()=>Ae((x==null?void 0:x.cuts.length)??0,!0),[Ae,x]);if(w.useEffect(()=>{ee(),Me(),$e()},[ee,Me,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[et,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:ee,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(te=>te.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:et,language:s,authFetch:i,targetLabel:gn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(te,ve)=>{const Y={...x,cuts:x.cuts.map(_e=>_e.id===q?{..._e,overlays:te,aiDraft:ve??_e.aiDraft??null}:_e)};if(!await be(Y))throw new Error("Failed to save overlays")},onExported:()=>ee(),onClose:()=>{R(null),ee()}});const Ue=x.cuts.reduce((te,ve)=>{const Y=r1(ve);return te[Y]++,te},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(te=>!gn(te)).length,_t=x.cuts.filter(te=>GS(te)).map(te=>te.id),At=uD({cuts:x.cuts,published:H.published}),Bt=((_r=At.steps.find(te=>te.key==="upload"))==null?void 0:_r.status)==="done",Ut=x.cuts.some(te=>te.finalImagePath&&!te.uploadedCid)||Bt&&!H.markdownReady,Vt=(nt??[]).filter(te=>te.state==="needs-conversion"&&te.convertiblePng).map(te=>({cutId:te.cutId,pngPath:te.convertiblePng})),an=new Map(Vt.map(te=>[te.cutId,te.pngPath])),ri=(nt??[]).filter(te=>te.state==="needs-conversion"&&te.issue).map(te=>te.issue),Mn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mi=et.match(/\d+/))==null?void 0:mi[0])??"0",10)+1}`,Bn=typeof x.title=="string"?x.title:null,cr=x.cuts.filter(te=>!gn(te)),Ii={cuts:x.cuts.length,artwork:cr.filter(te=>te.cleanImagePath||an.has(te.id)).length,converted:cr.filter(te=>te.cleanImagePath&&/\.(webp|jpe?g)$/i.test(te.cleanImagePath)).length,lettered:x.cuts.filter(te=>{var ve;return(((ve=te.overlays)==null?void 0:ve.length)??0)>0||!!te.finalImagePath}).length,uploaded:x.cuts.filter(te=>te.uploadedCid||te.uploadedUrl).length},vn=x.cuts.filter(te=>{var ve;return Bo(te)&&(((ve=te.overlays)==null?void 0:ve.length)??0)===0&&!te.finalImagePath&&!te.uploadedCid&&!te.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:Mn}),Bn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Bn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Ii.cuts," cuts · ",Ii.artwork," artwork found ·"," ",Ii.converted," converted · ",Ii.lettered," ","lettered · ",Ii.uploaded," uploaded"]})]}),vn>0&&d.jsx("button",{onClick:pi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${vn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{ue(!0),B([]);try{const te=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(te.ok){const ve=await te.json();B(ve.warnings||[])}}catch{}ue(!1)},disabled:ne,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:ne?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ne,disabled:U,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:U?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Xe,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"}),d.jsx("button",{onClick:Rt,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"}),d.jsx("button",{onClick:ot,disabled:re||!(x!=null&&x.cuts.some(te=>te.finalImagePath&&!te.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:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.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."]})]})]}),_t.length>0&&d.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:[_t.length===1?"Cut":"Cuts"," ",_t.join(", ")," ",_t.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",_t.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),it&&dt>0&&Ue.missing===0&&we.size===0&&d.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:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Vt.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Vt.length," PNG image",Vt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Yt(Vt),disabled:D,"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:D?"Converting…":"Convert all to WebP"})]}),d.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."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ri.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ri.map((te,ve)=>d.jsx("li",{children:te},ve))})]})]}),nt&&nt.length>0&&(()=>{const te=tM(nt),ve=nt.filter(Y=>Y.state==="missing");return d.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:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",te.uploaded," uploaded · ",te.finalReady," final ·"," ",te.cleanReady," clean · ",te.planned," planned",te.needsConversion>0?` · ${te.needsConversion} needs conversion`:"",te.missing>0?` · ${te.missing} missing`:""]}),ve.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ve.map(Y=>d.jsx("li",{children:Y.issue},Y.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:ye,onFinish:ot,finishing:re,progressText:G,canFinish:Ut,markdownReady:H.markdownReady,published:H.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((te,ve)=>{var Y;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ve,beforeLabel:ve===0?"Episode opening":`After cut ${(Y=x.cuts[ve-1])==null?void 0:Y.id}`,afterLabel:`Before cut ${te.id}`,disabled:U,onAdd:()=>Ae(ve)}),d.jsx(sM,{cut:te,storyName:e,plotFile:et,language:s,expanded:I===te.id,onToggle:()=>A(I===te.id?null:te.id),authFetch:i,onUpdated:()=>{ee(),Me(),$e()},onOpenEditor:()=>R(te.id),detectedLocalClean:ze.has(te.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Gt(te.id,{openEditor:!0})},aiDrafting:K===te.id,staleMessages:we.get(te.id)??[],onRepairStale:Ht,repairing:xe,conversionPng:an.get(te.id)??null,onConvert:St,converting:D,rowRef:me=>{me?vi.current.set(te.id,me):vi.current.delete(te.id)}})]},te.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Zt=x.cuts[x.cuts.length-1])==null?void 0:Zt.id}`,afterLabel:"Episode ending",disabled:U,onAdd:()=>Ae(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(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 Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(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 Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Uo(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 dM(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 Ip(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 Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(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 _M={...ml,attributes:{...ml.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(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 yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||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 SM(e){return e==="open-cuts"||e==="open-lettering"||e==="upload"||e==="refresh-assets"}function wM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:L=null,onWorkflowActionHandled:I}){const[A,q]=w.useState(null),[R,ne]=w.useState(!1),[ue,ye]=w.useState("preview"),[B,re]=w.useState("publish"),[$,G]=w.useState("text"),[V,H]=w.useState(null),T=w.useCallback((se,Ee)=>{ye("edit"),H(je=>({cutId:se,openEditor:Ee,seq:((je==null?void 0:je.seq)??0)+1}))},[]),[z,F]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,he]=w.useState(""),[ge,De]=w.useState(""),[ze,Fe]=w.useState(!1),[we,He]=w.useState(null),[it,st]=w.useState(0),[nt,Nt]=w.useState(0),[Be,ct]=w.useState(null),[Te,Wt]=w.useState(null),[vi,Ct]=w.useState(null),[et,ee]=w.useState(0),be=w.useRef(null),Me=w.useRef(!1),[$e,Xe]=w.useState(!1),[Gt,pi]=w.useState(hl[0]),[Rt,St]=w.useState(rs[0]),[Yt,ot]=w.useState(!1),[Ht,U]=w.useState(null),[Ce,Ae]=w.useState(null),[Ne,Ge]=w.useState(!1),[Ue,dt]=w.useState(!1),[_t,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Vt,an]=w.useState(!1),ri=w.useRef(null),Mn=w.useRef(null),[Bn,cr]=w.useState(!1),[Ii,vn]=w.useState(null),[_r,mi]=w.useState(null),[Zt,te]=w.useState("unknown"),ve=w.useRef(!1),[Y,me]=w.useState(!1),[_e,Oe]=w.useState(!1),[Pe,qe]=w.useState(null),[wt,vt]=w.useState([]),[jt,Ze]=w.useState(null),Qe=w.useRef(null),Kt=w.useRef(null),Ri=w.useRef(0),gi=w.useRef(!1);gi.current=SM(L==null?void 0:L.action);const li=w.useCallback(async()=>{if(!e||!t){q(null);return}const se=`${e}/${t}`,Ee=Kt.current!==se;Ee&&(Kt.current=se);try{const je=await i(`/api/stories/${e}/${t}`);if(je.ok){const Je=await je.json();q(Je),(Ee||!Me.current)&&(F(Je.content??""),Ee&&(X(!1),Me.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{ne(!0),li().finally(()=>ne(!1))},[li]),w.useEffect(()=>{if(!e||!t||ue==="edit"&&D)return;const se=setInterval(li,3e3);return()=>clearInterval(se)},[e,t,li,ue,D]);const[Di,yn]=w.useState(null),Br=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Br||!e){yn(null);return}let se=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{se||yn(Ee?Op(Ee.cuts||[]):null)}).catch(()=>{se||yn(null)}),()=>{se=!0}},[Br,e,i]);const qs=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qs||!e||!t){He(null),st(0),Nt(0),ct(null);return}let se=!1;const Ee=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[je,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Ee}`)]);if(se)return;if(!Je.ok){He("error"),st(0),Nt(0),ct(null);return}const Lt=await Je.json(),Mi=Lt.cuts||[],oi=je.ok?(await je.json()).content??"":"",wn=XS(oi,Mi);se||(He(wn.stage),st(wn.awaitingCount),Nt(wn.totalCuts),ct(Op(Mi)),Ct(typeof Lt.title=="string"?Lt.title:null))}catch{se||(He("error"),st(0),Nt(0),ct(null))}})(),()=>{se=!0}},[qs,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,et]),w.useEffect(()=>{if(!e){Wt(null);return}let se=!1;return i(`/api/stories/${e}/structure.md`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{se||Wt((Ee==null?void 0:Ee.content)??null)}).catch(()=>{}),()=>{se=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const se=Cu(p);let Ee=se??"";if(!se&&Te){const Je=Te.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(Ee=Cu(Je[1].replace(/\*+/g,"").trim())??"")}he(Ee);let je=h&&rs.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!je&&Te){const Je=Te.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(je=rs.find(Lt=>Lt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}De(je),Fe(f??!1)},[e,p,h,f,Te]);const br=w.useCallback(se=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}).catch(()=>{})},[e,i]),$t=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Me.current=!1,q(Ee=>Ee&&{...Ee,content:z}))}catch{}j(!1)}},[e,t,i,z]),Hi=w.useCallback(async()=>{if(!e||!t)return;const se=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${se}/generate-markdown`,{method:"POST"})).ok&&(await li(),ee(je=>je+1))}catch{}},[e,t,i,li]);w.useEffect(()=>{if(L&&L.seq!==Ri.current){switch(Ri.current=L.seq,L.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ye("edit"),G("cuts");break;case"generate-markdown":Hi();break;case"publish":ye("preview");break}I==null||I(L.seq)}},[L,x,Hi,I]);const yi=w.useCallback(se=>{var Je;const Ee=(Je=se.target.files)==null?void 0:Je[0];if(!Ee)return;ve.current=!0,vn(null),mi(null);const je=Sy(Ee);if(je){U(null),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ri.current&&(ri.current.value=""),Ut(je),te("invalid");return}U(Ee),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(Ee))),Ut(null),te("selected")},[]),Lr=w.useCallback(async se=>{var je;const Ee=(je=se.target.files)==null?void 0:je[0];if(Mn.current&&(Mn.current.value=""),!(!Ee||!e)){ve.current=!0,vn(null),cr(!0),Ut(null);try{let Je;try{Je=await Ku(Ee)}catch(Kn){U(null),Ae(hs=>(hs&&URL.revokeObjectURL(hs),null)),Ut(Kn instanceof Error?Kn.message:"Could not import image");return}const Lt=Je.type==="image/jpeg"?"jpg":"webp",Mi=new File([Je],`cover.${Lt}`,{type:Je.type}),oi=new FormData;oi.append("file",Mi);const wn=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:oi});if(!wn.ok){const Kn=await wn.json().catch(()=>({}));Ut(Kn.error||"Cover import failed");return}U(Mi),Ae(Kn=>(Kn&&URL.revokeObjectURL(Kn),URL.createObjectURL(Mi))),mi(null),te("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{cr(!1)}}},[e,i]),Or=w.useCallback(async se=>{if(se.size>1024*1024){qe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(se.type)){qe("Only WebP and JPEG images are accepted");return}Oe(!0),qe(null);try{const je=new FormData;je.append("file",se);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Upload failed")}const Lt=await Je.json();vt(Mi=>[...Mi,{cid:Lt.cid,url:Lt.url}])}catch(je){qe(je instanceof Error?je.message:"Upload failed")}finally{Oe(!1),Qe.current&&(Qe.current.value="")}},[i]),Qt=w.useCallback(se=>{var je;const Ee=(je=se.target.files)==null?void 0:je[0];Ee&&Or(Ee)},[Or]),Vn=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ge(!0),Ut(null),an(!1);try{let se;if(Ht){const je=new FormData;je.append("file",Ht);const Je=await i("/api/publish/upload-cover",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Cover upload failed")}se=(await Je.json()).cid}const Ee=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...se!==void 0&&{coverCid:se},genre:Gt,language:Rt,isNsfw:Yt})});if(!Ee.ok){const je=await Ee.json();throw new Error(je.error||"Update failed")}an(!0),U(null),se!==void 0&&(At(!0),Ae(je=>(je&&URL.revokeObjectURL(je),null)),te("unknown"),ri.current&&(ri.current.value="")),setTimeout(()=>an(!1),3e3)}catch(se){Ut(se instanceof Error?se.message:"Update failed")}finally{Ge(!1)}}},[A==null?void 0:A.storylineId,Ht,Gt,Rt,Yt,i]);w.useEffect(()=>{Xe(!1),U(null),Ae(null),Ut(null),an(!1),dt(!1),me(!1),vt([]),qe(null),vn(null),mi(null),te("unknown"),ve.current=!1,G(gi.current?"cuts":"text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||ve.current)return;let se=!1;return(async()=>{try{const Ee=await i(`/api/stories/${e}/cover-asset`);if(se||!Ee.ok)return;const je=await Ee.json();if(se)return;if(!(je!=null&&je.found)){te("none");return}if(!je.valid){mi(je.error||"Detected cover asset is invalid and was not used"),te("invalid");return}const Je=await i(`/api/stories/${e}/asset/${je.path.replace(/^assets\//,"")}`);if(se||!Je.ok)return;const Lt=await Je.blob(),Mi=new File([Lt],je.path.split("/").pop()||"cover.webp",{type:je.type});if(Sy(Mi)||se||ve.current)return;U(Mi),Ae(oi=>(oi&&URL.revokeObjectURL(oi),URL.createObjectURL(Mi))),vn(je.path),te("detected")}catch{}})(),()=>{se=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;dt(!1);const se="https://plotlink.xyz";let Ee=!1;return fetch(`${se}/api/storyline/${A.storylineId}`).then(je=>je.ok?je.json():null).then(je=>{if(!Ee){if(!je){Ut("Could not load current story metadata");return}if(je.genre){const Je=Cu(je.genre);Je&&pi(Je)}if(je.language){const Je=rs.find(Lt=>Lt.toLowerCase()===je.language.toLowerCase());Je&&St(Je)}je.isNsfw!==void 0&&ot(!!je.isNsfw),At(!!(je.coverCid||je.coverUrl||je.cover)),dt(!0)}}).catch(()=>{Ee||Ut("Could not load current story metadata")}),()=>{Ee=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(ue!=="edit")return;const se=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key==="s"&&(Ee.preventDefault(),$t())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[ue,$t]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const se=new Date(A.publishedAt).getTime(),Ee=300*1e3,je=()=>{const Lt=Math.max(0,Ee-(Date.now()-se));oe(Lt)};je();const Je=setInterval(je,1e3);return()=>clearInterval(Je)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const zr=ae!==null&&ae<=0,Ws=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Pr=(ue==="edit"?z:(A==null?void 0:A.content)??"").length,Si=t==="genesis.md",ur=t?/^plot-\d+\.md$/.test(t):!1,wi=c==="cartoon"&&ur,Ln=c==="cartoon"&&Si,cs=Ln||wi,On=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",Xo=S&&cs,vl=Ln?Di?Di.total:null:wi?we===null?null:nt:null,Sa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:On,cutCount:vl,cutProgress:Ln?Di:null}),wa=(Ln||wi)&&!On,Gs=wa?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:Te,contentType:"cartoon",episodeTitle:vi}):null,yl=!!Gs&&Uo(Gs,t),Ys=wi&&!On&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:vi}),dn=Ln&&!On?wm((A==null?void 0:A.content)??""):null,Ca=!!dn&&dn.blockers.length>0,Sl="w-full max-w-[32rem] rounded-xl border px-3 py-3",us={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ir=se=>{if(!Ln)return null;const Ee=cM({hasSelectedCover:!!Ht,invalid:Zt==="invalid",attached:se});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Ee.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${us[Ee.tone]}`,children:Ee.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},ka=yl||Ys,wl=()=>{if(!wa||!Gs)return null;const se=Si?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":yl?"true":"false","data-blocked":ka?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[se,":"]})," ",d.jsx("span",{className:ka?"text-error font-medium":"text-foreground",children:Gs})]}),yl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Si?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ys?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Gs,"” 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]})},Zo=()=>dn?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Ca?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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."}),dn.blockers.map((se,Ee)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:se},`b-${Ee}`)),dn.warnings.map((se,Ee)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:se},`w-${Ee}`))]}):null,hr=Si||ur?1e4:null,Sn=!On&&hr!==null&&Pr>hr,Cl=(A==null?void 0:A.content)??"",vr=On?{count:0,warnings:[]}:yM(Cl),dr=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:be,value:z,onChange:se=>{F(se.target.value),X(!0),Me.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,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:$t,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Xo&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${Sn?"text-error font-medium":"text-muted"}`,children:[Pr.toLocaleString(),hr!==null?`/${hr.toLocaleString()}`:" chars"]}),Sn&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Pr-hr).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ye("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ye("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),ue==="preview"?wi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>re("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>re("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:we}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):wi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Ln?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>G("text"),className:`px-2 py-0.5 text-[11px] rounded ${$==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>G("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${$==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:$==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):dr})]}):dr,!Xo&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:Sa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!zr&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),li())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${Ws?` (${Ws})`:""}`}),ur&&d.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,K,ge,ze)},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"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:Mn?Bn?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":Bn?"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."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var je;const ne=`https://plotlink.xyz/story/${A.storylineId}`;if(!Bn)return ne;const Ee=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((je=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:je[1])??"1");return`${ne}/${Ee}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),wi&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Xe(ne=>!ne),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&wi&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ir(_t),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{U(null),Ae(null),mi(null),te("unknown"),ai.current&&(ai.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ai,type:"file",accept:"image/webp,image/jpeg",onChange:Ii,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Wt,onChange:ne=>pi(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ol.map(ne=>d.jsx("option",{value:ne,children:ne},ne))}),d.jsx("select",{value:Rt,onChange:ne=>St(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:rs.map(ne=>d.jsx("option",{value:ne,children:ne},ne))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Gt,onChange:ne=>ot(ne.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:ei,disabled:Ne||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ne?"Saving...":Ue?"Save Changes":"Loading..."}),Yt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Xi&&Be&&Be.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Be.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withClean,"/",Be.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withText,"/",Be.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.uploaded,"/",Be.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Zi&&Jt&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Jt.total," planned",Jt.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Jt.withClean," clean ·"," ",Jt.withText," lettered ·"," ",Jt.exported," exported ·"," ",Jt.uploaded," uploaded"]})]}),(Zi||Xi)&&Sa&&d.jsxs("div",{className:`${vl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:Ko===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Zi?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:Sa})]}),Bn&&!Xi&&ue==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Y,onChange:ne=>me(ne.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Y&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 ne;return(ne=Qe.current)==null?void 0:ne.click()},onDragOver:ne=>{ne.preventDefault(),ne.stopPropagation()},onDrop:ne=>{var je;ne.preventDefault(),ne.stopPropagation();const Ee=(je=ne.dataTransfer.files)==null?void 0:je[0];Ee&&or(Ee)},children:[d.jsx("input",{ref:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:Gs,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:_e?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Pe&&d.jsx("span",{className:"text-error text-xs",children:Pe}),wt.map((ne,Ee)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ne.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ne.url})`),Ze(Ee),setTimeout(()=>Ze(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:jt===Ee?"Copied!":"Copy"})]})]},ne.cid))]})]}),wi&&c!=="cartoon"&&!(ue==="edit"&&$==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ir(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(ne=>(ne&&URL.revokeObjectURL(ne),null)),ai.current&&(ai.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ai,type:"file",accept:"image/webp,image/jpeg",onChange:Ii,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:An,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Di,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ne;return(ne=An.current)==null?void 0:ne.click()},disabled:Rn,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:Rn?"Importing…":"Import generated image (PNG ok)"}),Ht&&d.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."}),Pi&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Pi," — pick a file to override."]}),mr&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[mr," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Qt==="none"&&!Ht&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!us&&Zo(),!us&&Sl(),!us&&d.jsxs("div",{className:"flex items-center gap-2",children:[wi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:ne=>{he(ne.target.value),ne.target.value&&cs({genre:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),ol.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:ne=>{De(ne.target.value),ne.target.value&&cs({language:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),rs.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ds.count>0){const Ee=`This plot contains ${ds.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,K,ge,ze)},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"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:zr?ur?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":ur?"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."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var je;const se=`https://plotlink.xyz/story/${A.storylineId}`;if(!ur)return se;const Ee=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((je=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:je[1])??"1");return`${se}/${Ee}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Si&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Xe(se=>!se),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&Si&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ir(_t),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{U(null),Ae(null),mi(null),te("unknown"),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:yi,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Gt,onChange:se=>pi(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:hl.map(se=>d.jsx("option",{value:se,children:se},se))}),d.jsx("select",{value:Rt,onChange:se=>St(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:rs.map(se=>d.jsx("option",{value:se,children:se},se))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Yt,onChange:se=>ot(se.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Vn,disabled:Ne||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ne?"Saving...":Ue?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[wi&&Be&&Be.total>0&&d.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:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Be.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withClean,"/",Be.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withText,"/",Be.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.uploaded,"/",Be.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Ln&&Di&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Di.total," planned",Di.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Di.withClean," clean ·"," ",Di.withText," lettered ·"," ",Di.exported," exported ·"," ",Di.uploaded," uploaded"]})]}),(Ln||wi)&&Sa&&d.jsxs("div",{className:`${Sl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:vl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Ln?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:Sa})]}),ur&&!wi&&ue==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Y,onChange:se=>me(se.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Y&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.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 se;return(se=Qe.current)==null?void 0:se.click()},onDragOver:se=>{se.preventDefault(),se.stopPropagation()},onDrop:se=>{var je;se.preventDefault(),se.stopPropagation();const Ee=(je=se.dataTransfer.files)==null?void 0:je[0];Ee&&Or(Ee)},children:[d.jsx("input",{ref:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:Qt,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:_e?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Pe&&d.jsx("span",{className:"text-error text-xs",children:Pe}),wt.map((se,Ee)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.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:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",se.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${se.url})`),Ze(Ee),setTimeout(()=>Ze(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:jt===Ee?"Copied!":"Copy"})]})]},se.cid))]})]}),Si&&c!=="cartoon"&&!(ue==="edit"&&$==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ir(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(se=>(se&&URL.revokeObjectURL(se),null)),ri.current&&(ri.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"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:yi,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Mn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Lr,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var se;return(se=Mn.current)==null?void 0:se.click()},disabled:Bn,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:Bn?"Importing…":"Import generated image (PNG ok)"}),Ht&&d.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."}),Ii&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Ii," — pick a file to override."]}),_r&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[_r," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Zt==="none"&&!Ht&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.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."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!cs&&wl(),!cs&&Zo(),!cs&&d.jsxs("div",{className:"flex items-center gap-2",children:[Si&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:se=>{he(se.target.value),se.target.value&&br({genre:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),hl.map(se=>d.jsx("option",{value:se,children:se},se))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:se=>{De(se.target.value),se.target.value&&br({language:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),rs.map(se=>d.jsx("option",{value:se,children:se},se))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(vr.count>0){const Ee=`This plot contains ${vr.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(Ee))return}const ne=wi?Ht:null;ne?await(s==null?void 0:s(e,t,K,ge,ze,ne))&&(ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(je=>(je&&URL.revokeObjectURL(je),null)),ai.current&&(ai.current.value="")):s==null||s(e,t,K,ge,ze)},disabled:!!a||br||_r||Yn||wi&&(!K||!ge)||Xi&&we!=="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"}),wi&&c==="cartoon"&&(!K||!ge)&&d.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"}),wi&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),wi&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),br&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Xi&&we==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Xi&&we==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Xi&&we==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",tt," of ",it," ","still need an uploaded image"]})]}),us&&d.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 →"}),ds.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:ds.warnings.map((ne,Ee)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ne},Ee))}),wi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ze,onChange:ne=>{Fe(ne.target.checked),cs({isNsfw:ne.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),ze&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(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 s1(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(f=>!f.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 Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function kM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function EM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(NM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(kM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function NM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function jM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(LM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(PM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},TM={done:"✓",current:"◓",todo:"○"},AM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${AM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:TM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function RM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function DM(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(MM(a));return s}function MM(e){return{label:e.label,status:e.status,detail:e.detail}}const BM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function LM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:BM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=RM(t,i),p=DM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const OM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},zM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function PM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:OM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:zM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const IM=[{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 HM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:IM.map(s=>{const a=s.key===t;return d.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 UM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,O]=w.useState("cartoon"),[I,A]=w.useState("unknown"),[q,R]=w.useState(!1),[re,ue]=w.useState(!1),[ye,B]=w.useState(null),[se,$]=w.useState(!1),[G,V]=w.useState(null),[H,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),ue(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&rs.find(he=>he.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),O(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const F=w.useCallback(async()=>{R(!0),ue(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)ue(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){$(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(ze){B(ze instanceof Error?ze.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",he=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",he);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!De.ok){const ze=await De.json().catch(()=>({}));B(ze.error||"Cover import failed.");return}A("present"),V(ze=>(ze&&URL.revokeObjectURL(ze),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{$(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;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.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),ue(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),ue(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),ol.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),rs.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("button",{type:"button",onClick:j,"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:H?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),ue(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:F,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"}),re&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function $M({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function FM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var it,Nt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[O,I]=w.useState(null),[A,q]=w.useState(null),[R,re]=w.useState(null),[ue,ye]=w.useState(null),B=async()=>{try{const Be=await t(`/api/stories/${e}/cover-asset`),ct=Be.ok?await Be.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const qt=await Te.blob();return new File([qt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||qt.type})}catch{return null}};w.useEffect(()=>{let Be=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),qt=Te.ok?await Te.json():null;if(Be)return;!qt||!Array.isArray(qt.episodes)?(N(!0),x(null)):x(qt),v(!1)}catch{Be||(N(!0),x(null),v(!1))}})(),()=>{Be=!0}},[e,t,f]);const se=((Nt=(it=_==null?void 0:_.episodes)==null?void 0:it.find(Be=>!Be.published))==null?void 0:Nt.file)??null,$=se==="genesis.md",G=JSON.stringify([se??"",f]),[V,H]=w.useState(null);if(V!==G&&(H(G),I(null),q(null),re(null),ye(null)),w.useEffect(()=>{if(!se)return;let Be=!1;const ct=se.replace(/\.md$/,"");return(async()=>{var Te;try{const qt=[t(`/api/stories/${e}/${se}`),t(`/api/stories/${e}/cuts/${ct}`)];$&&qt.push(t(`/api/stories/${e}/structure.md`));const[yi,Ct,Je]=await Promise.all(qt);if(Be)return;if(I(yi.ok?(await yi.json()).content??"":""),Ct.ok){const ee=await Ct.json();if(Be)return;q(Array.isArray(ee.cuts)?ee.cuts:[]),re(typeof ee.title=="string"?ee.title:null)}else q(null),re(null);ye($&&Je&&Je.ok?((Te=await Je.json())==null?void 0:Te.content)??null:null)}catch{Be||(I(""),q(null),re(null),ye(null))}})(),()=>{Be=!0}},[se,$,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Be=>!Be.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=T.cuts,F=_.cover==="present",xe=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:F?"done":"todo",detail:F?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=O!==null,oe=ae?Nm({fileName:T.file,fileContent:O??"",storySlug:e,structureContent:ue,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Ho(oe,T.file),he=!X&&ae&&!Em({fileContent:O??"",episodeTitle:R}),ge=K||he,De=X&&ae?wm(O??""):null,ze=!!De&&De.blockers.length>0,Fe=!X&&ae&&A!==null?XS(O??"",A):null,we=Fe&&Fe.stage==="error"?Fe.issues:[],tt=j&&C&&(ae&&(X||A!==null))&&!ge&&!ze&&!Z&&!!a,st=async()=>{if(!(!tt||!a)){E(null);try{const Be=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Be)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Be,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Be.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Be.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Be.status==="done"?"✓":"○"}),d.jsx("span",{className:Be.status==="done"?"text-foreground":"text-muted",children:Be.label}),Be.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Be.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.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&&d.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":ze?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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((Be,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Be},`b-${ct}`)),De.warnings.map((Be,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Be},`w-${ct}`))]}),we.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(we).map(Be=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Be.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Be.title})},Be.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:we.map((Be,ct)=>d.jsx("li",{className:"font-mono break-words",children:Be},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!F&&d.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)"}),X&&!C&&d.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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.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 ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:st,disabled:!tt,"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:tt?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||ze?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:ze?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.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 qM(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 WM(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?Ho(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=qM(i,s);return a?Ho(a,t)||Ip(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 GM(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 h1="plotlink-panel-ratio",YM=.6,Ny=300,If=224,Hf=6;function VM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return YM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[O,I]=w.useState(VM),[A,q]=w.useState([]),[R,re]=w.useState(!1),[ue,ye]=w.useState(""),[B,se]=w.useState(""),[$,G]=w.useState(""),[V,H]=w.useState("English"),[T,z]=w.useState("normal"),[F,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[he,ge]=w.useState(new Set),[De,ze]=w.useState(new Set),[Fe,we]=w.useState({}),[He,tt]=w.useState({}),[st,it]=w.useState({}),[Nt,Be]=w.useState({}),[ct,Te]=w.useState({}),[qt,yi]=w.useState({}),[Ct,Je]=w.useState(!1),[ee,be]=w.useState(!0),[Me,$e]=w.useState(null),Xe=w.useRef(new Map),Wt=w.useRef(new Map),pi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Gt=w.useRef(0),ot=w.useRef(null),Ht=w.useRef(null),U=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(Y=>Y.ok?Y.json():null).then(Y=>{Y!=null&&Y.address&&E(Y.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(Y=>Y.ok?Y.json():null).then(Y=>{Y&&D(Y)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(O))}catch{}},[O]),w.useEffect(()=>{const Y=()=>{if(!Ht.current)return;const me=Ht.current.getBoundingClientRect().width-If-Hf;I(_e=>jy(_e,me))};return window.addEventListener("resize",Y),Y(),()=>window.removeEventListener("resize",Y)},[]);const Ce=w.useCallback(()=>{ye(""),se(""),G(""),z("normal"),xe("claude"),re(!0)},[]),Ae=w.useCallback(async(Y,me,_e,Oe)=>{const Pe=ue.trim();if(!Pe)return;const qe=Y==="cartoon"?"codex":Oe;try{const wt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Pe,description:B.trim()||void 0,language:me,genre:$||void 0,contentType:Y,agentMode:_e,agentProvider:qe})});if(!wt.ok)return;const vt=await wt.json();re(!1),we(jt=>({...jt,[vt.name]:Y})),tt(jt=>({...jt,[vt.name]:me})),$&&it(jt=>({...jt,[vt.name]:$})),K(jt=>({...jt,[vt.name]:qe})),_e==="bypass"&&ae(jt=>({...jt,[vt.name]:!0})),s(vt.name),o(null)}catch{}},[t,ue,B,$]);w.useEffect(()=>{if(A.length===0)return;const Y=setInterval(async()=>{try{const me=await t("/api/stories");if(!me.ok)return;const _e=await me.json(),Oe=new Set(_e.stories.filter(Pe=>Pe.name!=="_example").map(Pe=>Pe.name));for(const Pe of Oe)if(!St.current.has(Pe)&&A.length>0){const qe=A[0],wt=Xe.current.get(qe)||"fiction",vt=Wt.current.get(qe)||"English",jt=pi.current.get(qe)||"normal",Ze=Rt.current.get(qe)||"claude";let Qe=!1;ot.current&&(Qe=await ot.current(qe,Pe,{contentType:wt,language:vt,agentMode:jt,agentProvider:Ze}).catch(()=>!1)),Qe&&(q(Vt=>Vt.slice(1)),Xe.current.delete(qe),Wt.current.delete(qe),pi.current.delete(qe),Rt.current.delete(qe),jt==="bypass"&&ae(Vt=>{const Ri={...Vt,[Pe]:!0};return delete Ri[qe],Ri}),K(Vt=>{const Ri={...Vt,[Pe]:Ze};return delete Ri[qe],Ri}),t(`/api/stories/${Pe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:wt,language:vt,agentMode:jt,agentProvider:Ze})}).catch(()=>{})),s(Pe),o(null)}St.current=Oe}catch{}},3e3);return()=>clearInterval(Y)},[t,A]),w.useEffect(()=>{t("/api/stories").then(Y=>{if(Y.ok)return Y.json()}).then(Y=>{Y!=null&&Y.stories&&(St.current=new Set(Y.stories.filter(me=>me.name!=="_example").map(me=>me.name)))}).catch(()=>{})},[t]);const Ne=w.useCallback((Y,me)=>{s(Y),o(me),h(null)},[]),Ge=w.useRef(null),Ue=w.useCallback(async Y=>{var me,_e,Oe,Pe;Ge.current=Y,s(Y),o(null),h(null);try{const qe=await t(`/api/stories/${Y}`);if(qe.ok&&Ge.current===Y){const wt=await qe.json();if(wt.contentType==="cartoon")return;const vt=wt.files||[],Ze=((me=vt.map(Qe=>{var Vt;return{file:Qe.file,num:(Vt=Qe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Vt[1]}}).filter(Qe=>Qe.num!=null).sort((Qe,Vt)=>parseInt(Vt.num)-parseInt(Qe.num))[0])==null?void 0:me.file)??((_e=vt.find(Qe=>Qe.file==="genesis.md"))==null?void 0:_e.file)??((Oe=vt.find(Qe=>Qe.file==="structure.md"))==null?void 0:Oe.file)??((Pe=vt[0])==null?void 0:Pe.file);Ze&&Ge.current===Y&&o(Ze)}}catch{}},[t]),dt=w.useCallback(Y=>{Y.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const me=Oe=>{if(!U.current||!Ht.current)return;const Pe=Ht.current.getBoundingClientRect(),qe=Pe.width-If-Hf,wt=Oe.clientX-Pe.left-If;I(jy(wt/qe,qe))},_e=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",_e)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",_e)},[]),_t=w.useCallback(async(Y,me,_e,Oe,Pe,qe)=>{var Ze;f(me),v("Reading file..."),N(null);let wt=!1,vt=null,jt=!1;try{const Qe=await t(`/api/stories/${Y}/${me}`);if(!Qe.ok)throw new Error("Failed to read file");const Vt=await Qe.json(),Ri=Fe[Y];let Kt=null,Jt=null;if(me==="genesis.md")try{const Xt=await t(`/api/stories/${Y}/structure.md`);Xt.ok&&(Kt=(await Xt.json()).content??null)}catch{}else if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/))try{const Xt=await t(`/api/stories/${Y}/cuts/${me.replace(/\.md$/,"")}`);Xt.ok&&(Jt=(await Xt.json()).title??null)}catch{}const Gn=Nm({fileName:me,fileContent:Vt.content,storySlug:Y,structureContent:Kt,contentType:Ri,episodeTitle:Jt});if(Ri==="cartoon"&&Ho(Gn,me))return v(me==="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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/)&&!Em({fileContent:Vt.content,episodeTitle:Jt}))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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me==="genesis.md"){const Xt=wm(Vt.content).blockers;if(Xt.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Xt[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Dn;if(me.match(/^plot-\d+\.md$/)){if(pM(Vt)){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(()=>{f(null),v("")},6e3);return}try{const Xt=await t(`/api/stories/${Y}`);if(Xt.ok){const Di=(await Xt.json()).files.find(or=>or.file==="genesis.md"&&or.storylineId);Dn=Di==null?void 0:Di.storylineId}}catch{}if(!Dn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Xt=await t("/api/publish/preflight");if(Xt.ok){const Ii=await Xt.json();if(gM(Ii))return N(xM(Ii)),f(null),v(""),!1}}catch{}v("Publishing...");const Br=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:Y,fileName:me,title:Gn,content:Vt.content,genre:_e,language:Oe,isNsfw:Pe,storylineId:Dn,...wy(Fe,Y,Dn)?{contentType:wy(Fe,Y,Dn)}:{}})});if(!Br.ok){const Xt=await Br.json();throw new Error(Xt.error||"Publish failed")}const cs=(Ze=Br.body)==null?void 0:Ze.getReader(),gr=new TextDecoder;if(cs)for(;;){const{done:Xt,value:Ii}=await cs.read();if(Xt)break;const or=gr.decode(Ii).split(` -`).filter(Gs=>Gs.startsWith("data: "));for(const Gs of or)try{const ei=JSON.parse(Gs.slice(6));if(ei.step&&v(ei.message||ei.step),ei.step==="done"&&ei.txHash){if(jt=!0,await t(`/api/stories/${Y}/${me}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:ei.txHash,storylineId:ei.storylineId,plotIndex:ei.plotIndex,contentCid:ei.contentCid,gasCost:ei.gasCost,indexError:ei.indexError,authorAddress:M})}),x(Mn=>Mn+1),qe&&me==="genesis.md"&&ei.storylineId){v("Uploading cover...");let Mn=null;try{Mn=await uM(t,ei.storylineId,qe)}catch{}Mn||(wt=!0)}if(Ri==="cartoon"&&ei.storylineId)try{const Mn=me!=="genesis.md",Lr=`storylineId=${ei.storylineId}`+(Mn&&ei.plotIndex!=null?`&plotIndex=${ei.plotIndex}`:""),xl=await t(`/api/publish/public-title?${Lr}`);if(xl.ok){const Si=await xl.json(),wi=Mn?{plots:Si.plotTitle!=null?[{plotIndex:ei.plotIndex,title:Si.plotTitle}]:[]}:{title:Si.storylineTitle},Bn=WM({fileName:me,detail:wi,plotIndex:ei.plotIndex});Bn.ok||(vt=GM(Bn))}}catch{}}}catch{}}vt&&N(vt),v(wt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Qe){const Vt=Qe instanceof Error?Qe.message:"Publish failed";v(`Error: ${Vt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return jt&&!wt},[t,Fe,M]),At=w.useCallback(Y=>{Y.startsWith("_new_")&&(q(me=>me.filter(_e=>_e!==Y)),Xe.current.delete(Y),Wt.current.delete(Y),pi.current.delete(Y),Rt.current.delete(Y),ae(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}),K(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}))},[]);w.useEffect(()=>{const Y=_e=>{ge(new Set(_e.filter(Ze=>Ze.hasStructure).map(Ze=>Ze.name))),ze(new Set(_e.filter(Ze=>Ze.hasGenesis).map(Ze=>Ze.name)));const Oe={},Pe={},qe={},wt={},vt={},jt={};for(const Ze of _e)Oe[Ze.name]=Ze.contentType||"fiction",Pe[Ze.name]=Ze.language,qe[Ze.name]=Ze.genre,wt[Ze.name]=Ze.isNsfw,vt[Ze.name]=Ze.agentProvider,Ze.title&&(jt[Ze.name]=Ze.title);we(Oe),tt(Pe),it(qe),Be(wt),yi(vt),Te(jt)};t("/api/stories").then(_e=>_e.ok?_e.json():null).then(_e=>{_e!=null&&_e.stories&&Y(_e.stories)}).catch(()=>{});const me=setInterval(async()=>{try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();Y(Oe.stories)}}catch{}},5e3);return()=>clearInterval(me)},[t]);const Bt=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Ut=!!j&&!Bt,Yt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),an=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const Y=i;if((await t(`/api/stories/${Y}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){yi(_e=>({..._e,[Y]:"codex"})),K(_e=>({..._e,[Y]:"codex"}));try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();if(Oe!=null&&Oe.stories){const Pe={};for(const qe of Oe.stories)Pe[qe.name]=qe.agentProvider;yi(Pe)}}}catch{}}},[t,i]),ai=w.useCallback(Y=>{i===Y&&(s(null),o(null))},[i]),An=i?oe[i]??qt[i]:void 0,Rn=Of(i,Fe,Xe.current),lr=mM(Rn,An,i),Pi=!!i&&Rn==="cartoon",vn=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",mr=w.useCallback(Y=>{const me=i;if(me)switch(Y){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ne(me,"structure.md");break;case"genesis":Ne(me,"genesis.md");break;case"publish":h("publish");break}},[i,Ne]),mi=w.useCallback((Y,me)=>{const _e=i;if(!_e)return;const Oe=Pe=>{Gt.current+=1,$e({action:Pe,seq:Gt.current})};switch(Y){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":if(!me)return;Ne(_e,me),Oe(Y);break}},[i,Ne]),Qt=w.useCallback(Y=>{i&&(Y.genre!==void 0&&it(me=>({...me,[i]:Y.genre||void 0})),Y.language!==void 0&&tt(me=>({...me,[i]:Y.language||void 0})),Y.isNsfw!==void 0&&Be(me=>({...me,[i]:Y.isNsfw})))},[i]),te=w.useCallback(Y=>{Je(Y),be(!Y)},[]),ve=Ct&&!ee;return d.jsxs("div",{ref:Ht,className:"h-[calc(100vh-3.5rem)] flex","data-testid":ve?"stories-focused-lettering-mode":"stories-default-layout",children:[!ve&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ne,onNewStory:Ce,untitledSessions:A})}),!ve&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${O} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ue,onDestroySession:At,onArchiveStory:ai,confirmedStories:he,renameRef:ot,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Xe.current),needsProviderRepair:lr,onRepairProvider:an})}),!ve&&d.jsx("div",{onMouseDown:dt,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:ve?{flex:"1 0 0"}:{flex:`${1-O} 0 0`},children:[!Ct&&Pi&&i&&d.jsx(HM,{storyTitle:ct[i]||i,active:vn,onSelect:mr}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:Pi&&c==="story-info"&&i?d.jsx(UM,{storyName:i,authFetch:t,onSaved:Qt}):Pi&&c==="episodes"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:Ne}):Pi&&c==="publish"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ne,onOpenStoryInfo:()=>h("story-info"),onPublish:_t,publishingFile:p,genre:st[i],language:He[i],isNsfw:Nt[i],refreshKey:_}):i&&!a?d.jsx(jM,{storyName:i,authFetch:t,onOpenFile:Ne}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:_t,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Xe.current)||"fiction",language:i?He[i]:void 0,genre:i?st[i]:void 0,isNsfw:i?Nt[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:Y=>i&&Ne(i,Y),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:ee,onFocusedLetteringModeChange:te,onFocusedLetteringWorkspaceVisibleChange:be,workflowActionRequest:Me,onWorkflowActionHandled:Y=>$e(me=>(me==null?void 0:me.seq)===Y?null:me)})}),!Ct&&Pi&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(EM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:mi,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:ue,onChange:Y=>ye(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:Y=>se(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:$,onChange:Y=>G(Y.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:[d.jsx("option",{value:"",children:"— Select later —"}),ol.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:Y=>H(Y.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:rs.map(Y=>d.jsx("option",{value:Y,children:Y},Y))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:Y=>z(Y.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:F,onChange:Y=>xe(Y.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:F==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!ue.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>Ae("fiction",V,T,F),disabled:!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>Ae("cartoon",V,T,"codex"),disabled:Ut||!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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."})]}),j&&!j.codex.installed&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Yt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>re(!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 XM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 ZM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(XM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function QM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(ZM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(QM,{})}));export{zp as M,jo as a,$S as b,$D as c,$3 as d,No as l,ym as s,YS as t,n4 as v}; +Publish now?`;if(!window.confirm(Ee))return}const se=Si?Ht:null;se?await(s==null?void 0:s(e,t,K,ge,ze,se))&&(ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(je=>(je&&URL.revokeObjectURL(je),null)),ri.current&&(ri.current.value="")):s==null||s(e,t,K,ge,ze)},disabled:!!a||Sn||ka||Ca||Si&&(!K||!ge)||wi&&we!=="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"}),Si&&c==="cartoon"&&(!K||!ge)&&d.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"}),Si&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Si&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),Sn&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),wi&&we==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),wi&&we==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),wi&&we==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",it," of ",nt," ","still need an uploaded image"]})]}),cs&&d.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 →"}),vr.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:vr.warnings.map((se,Ee)=>d.jsx("span",{className:"text-amber-600 text-xs",children:se},Ee))}),Si&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ze,onChange:se=>{Fe(se.target.checked),br({isNsfw:se.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),ze&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function CM(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 s1(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(f=>!f.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 Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full 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 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function kM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:CM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function EM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(kM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function NM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(jM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(EM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function jM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function TM({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 _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.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)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(OM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(IM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.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"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},AM={done:"✓",current:"◓",todo:"○"},RM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${RM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:AM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.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,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function DM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function MM(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(BM(a));return s}function BM(e){return{label:e.label,status:e.status,detail:e.detail}}const LM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function OM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:LM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=DM(t,i),p=MM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.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:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const zM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},PM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function IM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.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:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.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}),d.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"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.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:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:zM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:PM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.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:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const HM=[{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 UM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:HM.map(s=>{const a=s.key===t;return d.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 $M({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,L]=w.useState("cartoon"),[I,A]=w.useState("unknown"),[q,R]=w.useState(!1),[ne,ue]=w.useState(!1),[ye,B]=w.useState(null),[re,$]=w.useState(!1),[G,V]=w.useState(null),[H,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),ue(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&rs.find(he=>he.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),L(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const F=w.useCallback(async()=>{R(!0),ue(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)ue(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){$(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(ze){B(ze instanceof Error?ze.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",he=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",he);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!De.ok){const ze=await De.json().catch(()=>({}));B(ze.error||"Cover import failed.");return}A("present"),V(ze=>(ze&&URL.revokeObjectURL(ze),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{$(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;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.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.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 d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),ue(!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"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),ue(!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"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),hl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),ue(!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:[d.jsx("option",{value:"",children:"Needs metadata"}),rs.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.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"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.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"}),d.jsx("button",{type:"button",onClick:j,"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:H?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),ue(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:F,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"}),ne&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function FM({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 f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.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?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.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?d.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."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.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:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function qM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var nt,Nt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[L,I]=w.useState(null),[A,q]=w.useState(null),[R,ne]=w.useState(null),[ue,ye]=w.useState(null),B=async()=>{try{const Be=await t(`/api/stories/${e}/cover-asset`),ct=Be.ok?await Be.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Wt=await Te.blob();return new File([Wt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||Wt.type})}catch{return null}};w.useEffect(()=>{let Be=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),Wt=Te.ok?await Te.json():null;if(Be)return;!Wt||!Array.isArray(Wt.episodes)?(N(!0),x(null)):x(Wt),v(!1)}catch{Be||(N(!0),x(null),v(!1))}})(),()=>{Be=!0}},[e,t,f]);const re=((Nt=(nt=_==null?void 0:_.episodes)==null?void 0:nt.find(Be=>!Be.published))==null?void 0:Nt.file)??null,$=re==="genesis.md",G=JSON.stringify([re??"",f]),[V,H]=w.useState(null);if(V!==G&&(H(G),I(null),q(null),ne(null),ye(null)),w.useEffect(()=>{if(!re)return;let Be=!1;const ct=re.replace(/\.md$/,"");return(async()=>{var Te;try{const Wt=[t(`/api/stories/${e}/${re}`),t(`/api/stories/${e}/cuts/${ct}`)];$&&Wt.push(t(`/api/stories/${e}/structure.md`));const[vi,Ct,et]=await Promise.all(Wt);if(Be)return;if(I(vi.ok?(await vi.json()).content??"":""),Ct.ok){const ee=await Ct.json();if(Be)return;q(Array.isArray(ee.cuts)?ee.cuts:[]),ne(typeof ee.title=="string"?ee.title:null)}else q(null),ne(null);ye($&&et&&et.ok?((Te=await et.json())==null?void 0:Te.content)??null:null)}catch{Be||(I(""),q(null),ne(null),ye(null))}})(),()=>{Be=!0}},[re,$,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Be=>!Be.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.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 z=T.cuts,F=_.cover==="present",xe=[{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.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`: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:F?"done":"todo",detail:F?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=L!==null,oe=ae?Nm({fileName:T.file,fileContent:L??"",storySlug:e,structureContent:ue,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Uo(oe,T.file),he=!X&&ae&&!Em({fileContent:L??"",episodeTitle:R}),ge=K||he,De=X&&ae?wm(L??""):null,ze=!!De&&De.blockers.length>0,Fe=!X&&ae&&A!==null?XS(L??"",A):null,we=Fe&&Fe.stage==="error"?Fe.issues:[],it=j&&C&&(ae&&(X||A!==null))&&!ge&&!ze&&!Z&&!!a,st=async()=>{if(!(!it||!a)){E(null);try{const Be=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Be)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Be,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Be.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Be.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Be.status==="done"?"✓":"○"}),d.jsx("span",{className:Be.status==="done"?"text-foreground":"text-muted",children:Be.label}),Be.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Be.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.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&&d.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":ze?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.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((Be,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Be},`b-${ct}`)),De.warnings.map((Be,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Be},`w-${ct}`))]}),we.length>0&&d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.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"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(we).map(Be=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Be.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Be.title})},Be.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:we.map((Be,ct)=>d.jsx("li",{className:"font-mono break-words",children:Be},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!F&&d.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)"}),X&&!C&&d.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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.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 ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:st,disabled:!it,"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:it?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||ze?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:ze?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.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 WM(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 GM(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?Uo(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=WM(i,s);return a?Uo(a,t)||Ip(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 YM(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 h1="plotlink-panel-ratio",VM=.6,Ny=300,If=224,Hf=6;function KM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return VM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function XM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[L,I]=w.useState(KM),[A,q]=w.useState([]),[R,ne]=w.useState(!1),[ue,ye]=w.useState(""),[B,re]=w.useState(""),[$,G]=w.useState(""),[V,H]=w.useState("English"),[T,z]=w.useState("normal"),[F,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[he,ge]=w.useState(new Set),[De,ze]=w.useState(new Set),[Fe,we]=w.useState({}),[He,it]=w.useState({}),[st,nt]=w.useState({}),[Nt,Be]=w.useState({}),[ct,Te]=w.useState({}),[Wt,vi]=w.useState({}),[Ct,et]=w.useState(!1),[ee,be]=w.useState(!0),[Me,$e]=w.useState(null),Xe=w.useRef(new Map),Gt=w.useRef(new Map),pi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Yt=w.useRef(0),ot=w.useRef(null),Ht=w.useRef(null),U=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(Y=>Y.ok?Y.json():null).then(Y=>{Y!=null&&Y.address&&E(Y.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(Y=>Y.ok?Y.json():null).then(Y=>{Y&&D(Y)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(L))}catch{}},[L]),w.useEffect(()=>{const Y=()=>{if(!Ht.current)return;const me=Ht.current.getBoundingClientRect().width-If-Hf;I(_e=>jy(_e,me))};return window.addEventListener("resize",Y),Y(),()=>window.removeEventListener("resize",Y)},[]);const Ce=w.useCallback(()=>{ye(""),re(""),G(""),z("normal"),xe("claude"),ne(!0)},[]),Ae=w.useCallback(async(Y,me,_e,Oe)=>{const Pe=ue.trim();if(!Pe)return;const qe=Y==="cartoon"?"codex":Oe;try{const wt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Pe,description:B.trim()||void 0,language:me,genre:$||void 0,contentType:Y,agentMode:_e,agentProvider:qe})});if(!wt.ok)return;const vt=await wt.json();ne(!1),we(jt=>({...jt,[vt.name]:Y})),it(jt=>({...jt,[vt.name]:me})),$&&nt(jt=>({...jt,[vt.name]:$})),K(jt=>({...jt,[vt.name]:qe})),_e==="bypass"&&ae(jt=>({...jt,[vt.name]:!0})),s(vt.name),o(null)}catch{}},[t,ue,B,$]);w.useEffect(()=>{if(A.length===0)return;const Y=setInterval(async()=>{try{const me=await t("/api/stories");if(!me.ok)return;const _e=await me.json(),Oe=new Set(_e.stories.filter(Pe=>Pe.name!=="_example").map(Pe=>Pe.name));for(const Pe of Oe)if(!St.current.has(Pe)&&A.length>0){const qe=A[0],wt=Xe.current.get(qe)||"fiction",vt=Gt.current.get(qe)||"English",jt=pi.current.get(qe)||"normal",Ze=Rt.current.get(qe)||"claude";let Qe=!1;ot.current&&(Qe=await ot.current(qe,Pe,{contentType:wt,language:vt,agentMode:jt,agentProvider:Ze}).catch(()=>!1)),Qe&&(q(Kt=>Kt.slice(1)),Xe.current.delete(qe),Gt.current.delete(qe),pi.current.delete(qe),Rt.current.delete(qe),jt==="bypass"&&ae(Kt=>{const Ri={...Kt,[Pe]:!0};return delete Ri[qe],Ri}),K(Kt=>{const Ri={...Kt,[Pe]:Ze};return delete Ri[qe],Ri}),t(`/api/stories/${Pe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:wt,language:vt,agentMode:jt,agentProvider:Ze})}).catch(()=>{})),s(Pe),o(null)}St.current=Oe}catch{}},3e3);return()=>clearInterval(Y)},[t,A]),w.useEffect(()=>{t("/api/stories").then(Y=>{if(Y.ok)return Y.json()}).then(Y=>{Y!=null&&Y.stories&&(St.current=new Set(Y.stories.filter(me=>me.name!=="_example").map(me=>me.name)))}).catch(()=>{})},[t]);const Ne=w.useCallback((Y,me)=>{s(Y),o(me),h(null)},[]),Ge=w.useRef(null),Ue=w.useCallback(async Y=>{var me,_e,Oe,Pe;Ge.current=Y,s(Y),o(null),h(null);try{const qe=await t(`/api/stories/${Y}`);if(qe.ok&&Ge.current===Y){const wt=await qe.json();if(wt.contentType==="cartoon")return;const vt=wt.files||[],Ze=((me=vt.map(Qe=>{var Kt;return{file:Qe.file,num:(Kt=Qe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Kt[1]}}).filter(Qe=>Qe.num!=null).sort((Qe,Kt)=>parseInt(Kt.num)-parseInt(Qe.num))[0])==null?void 0:me.file)??((_e=vt.find(Qe=>Qe.file==="genesis.md"))==null?void 0:_e.file)??((Oe=vt.find(Qe=>Qe.file==="structure.md"))==null?void 0:Oe.file)??((Pe=vt[0])==null?void 0:Pe.file);Ze&&Ge.current===Y&&o(Ze)}}catch{}},[t]),dt=w.useCallback(Y=>{Y.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const me=Oe=>{if(!U.current||!Ht.current)return;const Pe=Ht.current.getBoundingClientRect(),qe=Pe.width-If-Hf,wt=Oe.clientX-Pe.left-If;I(jy(wt/qe,qe))},_e=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",_e)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",_e)},[]),_t=w.useCallback(async(Y,me,_e,Oe,Pe,qe)=>{var Ze;f(me),v("Reading file..."),N(null);let wt=!1,vt=null,jt=!1;try{const Qe=await t(`/api/stories/${Y}/${me}`);if(!Qe.ok)throw new Error("Failed to read file");const Kt=await Qe.json(),Ri=Fe[Y];let gi=null,li=null;if(me==="genesis.md")try{const $t=await t(`/api/stories/${Y}/structure.md`);$t.ok&&(gi=(await $t.json()).content??null)}catch{}else if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/))try{const $t=await t(`/api/stories/${Y}/cuts/${me.replace(/\.md$/,"")}`);$t.ok&&(li=(await $t.json()).title??null)}catch{}const Di=Nm({fileName:me,fileContent:Kt.content,storySlug:Y,structureContent:gi,contentType:Ri,episodeTitle:li});if(Ri==="cartoon"&&Uo(Di,me))return v(me==="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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/)&&!Em({fileContent:Kt.content,episodeTitle:li}))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(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me==="genesis.md"){const $t=wm(Kt.content).blockers;if($t.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${$t[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let yn;if(me.match(/^plot-\d+\.md$/)){if(pM(Kt)){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(()=>{f(null),v("")},6e3);return}try{const $t=await t(`/api/stories/${Y}`);if($t.ok){const yi=(await $t.json()).files.find(Lr=>Lr.file==="genesis.md"&&Lr.storylineId);yn=yi==null?void 0:yi.storylineId}}catch{}if(!yn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const $t=await t("/api/publish/preflight");if($t.ok){const Hi=await $t.json();if(gM(Hi))return N(xM(Hi)),f(null),v(""),!1}}catch{}v("Publishing...");const Br=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:Y,fileName:me,title:Di,content:Kt.content,genre:_e,language:Oe,isNsfw:Pe,storylineId:yn,...wy(Fe,Y,yn)?{contentType:wy(Fe,Y,yn)}:{}})});if(!Br.ok){const $t=await Br.json();throw new Error($t.error||"Publish failed")}const qs=(Ze=Br.body)==null?void 0:Ze.getReader(),br=new TextDecoder;if(qs)for(;;){const{done:$t,value:Hi}=await qs.read();if($t)break;const Lr=br.decode(Hi).split(` +`).filter(Or=>Or.startsWith("data: "));for(const Or of Lr)try{const Qt=JSON.parse(Or.slice(6));if(Qt.step&&v(Qt.message||Qt.step),Qt.step==="done"&&Qt.txHash){if(jt=!0,await t(`/api/stories/${Y}/${me}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Qt.txHash,storylineId:Qt.storylineId,plotIndex:Qt.plotIndex,contentCid:Qt.contentCid,gasCost:Qt.gasCost,indexError:Qt.indexError,authorAddress:M})}),x(Vn=>Vn+1),qe&&me==="genesis.md"&&Qt.storylineId){v("Uploading cover...");let Vn=null;try{Vn=await uM(t,Qt.storylineId,qe)}catch{}Vn||(wt=!0)}if(Ri==="cartoon"&&Qt.storylineId)try{const Vn=me!=="genesis.md",zr=`storylineId=${Qt.storylineId}`+(Vn&&Qt.plotIndex!=null?`&plotIndex=${Qt.plotIndex}`:""),Ws=await t(`/api/publish/public-title?${zr}`);if(Ws.ok){const Zi=await Ws.json(),Pr=Vn?{plots:Zi.plotTitle!=null?[{plotIndex:Qt.plotIndex,title:Zi.plotTitle}]:[]}:{title:Zi.storylineTitle},Si=GM({fileName:me,detail:Pr,plotIndex:Qt.plotIndex});Si.ok||(vt=YM(Si))}}catch{}}}catch{}}vt&&N(vt),v(wt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Qe){const Kt=Qe instanceof Error?Qe.message:"Publish failed";v(`Error: ${Kt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return jt&&!wt},[t,Fe,M]),At=w.useCallback(Y=>{Y.startsWith("_new_")&&(q(me=>me.filter(_e=>_e!==Y)),Xe.current.delete(Y),Gt.current.delete(Y),pi.current.delete(Y),Rt.current.delete(Y),ae(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}),K(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}))},[]);w.useEffect(()=>{const Y=_e=>{ge(new Set(_e.filter(Ze=>Ze.hasStructure).map(Ze=>Ze.name))),ze(new Set(_e.filter(Ze=>Ze.hasGenesis).map(Ze=>Ze.name)));const Oe={},Pe={},qe={},wt={},vt={},jt={};for(const Ze of _e)Oe[Ze.name]=Ze.contentType||"fiction",Pe[Ze.name]=Ze.language,qe[Ze.name]=Ze.genre,wt[Ze.name]=Ze.isNsfw,vt[Ze.name]=Ze.agentProvider,Ze.title&&(jt[Ze.name]=Ze.title);we(Oe),it(Pe),nt(qe),Be(wt),vi(vt),Te(jt)};t("/api/stories").then(_e=>_e.ok?_e.json():null).then(_e=>{_e!=null&&_e.stories&&Y(_e.stories)}).catch(()=>{});const me=setInterval(async()=>{try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();Y(Oe.stories)}}catch{}},5e3);return()=>clearInterval(me)},[t]);const Bt=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Ut=!!j&&!Bt,Vt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),an=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const Y=i;if((await t(`/api/stories/${Y}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){vi(_e=>({..._e,[Y]:"codex"})),K(_e=>({..._e,[Y]:"codex"}));try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();if(Oe!=null&&Oe.stories){const Pe={};for(const qe of Oe.stories)Pe[qe.name]=qe.agentProvider;vi(Pe)}}}catch{}}},[t,i]),ri=w.useCallback(Y=>{i===Y&&(s(null),o(null))},[i]),Mn=i?oe[i]??Wt[i]:void 0,Bn=Of(i,Fe,Xe.current),cr=mM(Bn,Mn,i),Ii=!!i&&Bn==="cartoon",vn=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",_r=w.useCallback(Y=>{const me=i;if(me)switch(Y){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ne(me,"structure.md");break;case"genesis":Ne(me,"genesis.md");break;case"publish":h("publish");break}},[i,Ne]),mi=w.useCallback((Y,me)=>{const _e=i;if(!_e)return;const Oe=Pe=>{Yt.current+=1,$e({action:Pe,seq:Yt.current})};switch(Y){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":if(!me)return;Ne(_e,me),Oe(Y);break}},[i,Ne]),Zt=w.useCallback(Y=>{i&&(Y.genre!==void 0&&nt(me=>({...me,[i]:Y.genre||void 0})),Y.language!==void 0&&it(me=>({...me,[i]:Y.language||void 0})),Y.isNsfw!==void 0&&Be(me=>({...me,[i]:Y.isNsfw})))},[i]),te=w.useCallback(Y=>{et(Y),be(!Y)},[]),ve=Ct&&!ee;return d.jsxs("div",{ref:Ht,className:"h-[calc(100vh-3.5rem)] flex","data-testid":ve?"stories-focused-lettering-mode":"stories-default-layout",children:[!ve&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ne,onNewStory:Ce,untitledSessions:A})}),!ve&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${L} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ue,onDestroySession:At,onArchiveStory:ri,confirmedStories:he,renameRef:ot,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Xe.current),needsProviderRepair:cr,onRepairProvider:an})}),!ve&&d.jsx("div",{onMouseDown:dt,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:ve?{flex:"1 0 0"}:{flex:`${1-L} 0 0`},children:[!Ct&&Ii&&i&&d.jsx(UM,{storyTitle:ct[i]||i,active:vn,onSelect:_r}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:Ii&&c==="story-info"&&i?d.jsx($M,{storyName:i,authFetch:t,onSaved:Zt}):Ii&&c==="episodes"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ne}):Ii&&c==="publish"&&i?d.jsx(qM,{storyName:i,authFetch:t,onOpenFile:Ne,onOpenStoryInfo:()=>h("story-info"),onPublish:_t,publishingFile:p,genre:st[i],language:He[i],isNsfw:Nt[i],refreshKey:_}):i&&!a?d.jsx(TM,{storyName:i,authFetch:t,onOpenFile:Ne}):d.jsx(wM,{storyName:i,fileName:a,authFetch:t,onPublish:_t,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Xe.current)||"fiction",language:i?He[i]:void 0,genre:i?st[i]:void 0,isNsfw:i?Nt[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:Y=>i&&Ne(i,Y),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:ee,onFocusedLetteringModeChange:te,onFocusedLetteringWorkspaceVisibleChange:be,workflowActionRequest:Me,onWorkflowActionHandled:Y=>$e(me=>(me==null?void 0:me.seq)===Y?null:me)})}),!Ct&&Ii&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(NM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:mi,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 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:[d.jsx("span",{children:S}),d.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"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:ue,onChange:Y=>ye(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:Y=>re(Y.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"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:$,onChange:Y=>G(Y.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:[d.jsx("option",{value:"",children:"— Select later —"}),hl.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:Y=>H(Y.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:rs.map(Y=>d.jsx("option",{value:Y,children:Y},Y))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:Y=>z(Y.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:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:F,onChange:Y=>xe(Y.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:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:F==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!ue.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>Ae("fiction",V,T,F),disabled:!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>Ae("cartoon",V,T,"codex"),disabled:Ut||!ue.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:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.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."})]}),j&&!j.codex.installed&&d.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."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.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:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.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"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Vt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ne(!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 ZM({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 f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.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&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.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 QM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.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&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.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"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(XM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(ZM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function JM(){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(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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 f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),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?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(QM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(JM,{})}));export{zp as M,To as a,$S as b,$D as c,$3 as d,jo as l,ym as s,YS as t,r4 as v}; diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 454f503..ada5ffa 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,7 +7,7 @@ - +