From ee3f7d7422223a5b067be25c99067d451d7c1608 Mon Sep 17 00:00:00 2001 From: Project7 Date: Sun, 7 Jun 2026 08:49:58 +0000 Subject: [PATCH 1/2] Redesign cartoon lettering review workflow --- app/web/components/CutListPanel.test.tsx | 69 ++++-- app/web/components/CutListPanel.tsx | 210 +++++++++++------- app/web/components/LetteringEditor.test.tsx | 31 ++- app/web/components/LetteringEditor.tsx | 69 ++++-- ...cut-DAQ_YjPc.js => export-cut-BdY0Az65.js} | 2 +- app/web/dist/assets/index-B066-0l8.js | 143 ------------ app/web/dist/assets/index-Mt6kwRka.js | 143 ++++++++++++ ...{index-DP8e99_8.css => index-SgqE3Vv0.css} | 2 +- app/web/dist/index.html | 4 +- 9 files changed, 408 insertions(+), 265 deletions(-) rename app/web/dist/assets/{export-cut-DAQ_YjPc.js => export-cut-BdY0Az65.js} (98%) delete mode 100644 app/web/dist/assets/index-B066-0l8.js create mode 100644 app/web/dist/assets/index-Mt6kwRka.js rename app/web/dist/assets/{index-DP8e99_8.css => index-SgqE3Vv0.css} (56%) diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index 24ad877..4346bb9 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -100,7 +100,7 @@ describe("CutListPanel", () => { render(); await waitFor(() => { - expect(screen.getByText("Exported")).toBeInTheDocument(); + expect(screen.getByTestId("cut-card-status-1")).toHaveTextContent("Exported"); expect(screen.getByText("1 lettered")).toBeInTheDocument(); }); }); @@ -150,7 +150,7 @@ describe("CutListPanel", () => { const authFetch = mockAuthFetch({ ok: true, data: cutsData }); render(); - const scroll = await screen.findByTestId("cut-list-scroll"); + const scroll = await screen.findByTestId("lettering-review-board"); expect(scroll).toHaveClass("min-h-56"); fireEvent.click(screen.getByText("Cut 1 scene")); @@ -1021,10 +1021,11 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect(screen.getByTestId("cut-card-status-1")).toHaveTextContent("Needs conversion"); expect(screen.getByTestId("card-convert-1")).toBeInTheDocument(); expect(screen.getByTestId("cut-card-status-2")).toHaveTextContent("Ready for lettering"); - // A clean, un-lettered cut shows the first-class lettering choice (#442). - expect(screen.getByTestId("lettering-2")).toBeInTheDocument(); - expect(screen.getByTestId("add-bubbles-2")).toBeInTheDocument(); + expect(screen.getByTestId("lettering-review-state-2")).toHaveTextContent("Unlettered"); + expect(screen.getByTestId("add-bubbles-2")).toHaveTextContent("Open focused editor"); expect(screen.getByTestId("cut-card-status-3")).toHaveTextContent("Needs image"); + expect(screen.getByTestId("lettering-review-board")).toBeInTheDocument(); + expect(screen.getByTestId("between-scene-slot-1")).toHaveTextContent("Between-scene lettering"); // Technical controls live under a collapsed-by-default Details disclosure. const advanced = screen.getByTestId("cut-advanced"); @@ -1033,9 +1034,9 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect(within(advanced).getByTestId("sync-clean-btn")).toBeInTheDocument(); }); - // #442: lettering is a first-class, visible step with an intentional - // Manual vs AI-draft choice, and "Review lettering" once bubbles exist. - it("offers a Manual/AI-draft lettering choice on a clean cut and 'Review lettering' once bubbles exist", async () => { + // #488: AI drafting is scoped to the selected target inside the focused + // editor, while the review board stays focused on opening/editing targets. + it("opens a focused editor with scoped AI draft assistance and keeps review state visible", async () => { const overlay = { id: "o1", type: "speech", x: 0.1, y: 0.1, width: 0.3, height: 0.15, text: "Hi", speaker: "Sera" }; const fn = vi.fn((url: string) => { if (url.includes("/asset-diagnostics")) { @@ -1057,24 +1058,60 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { render(); await screen.findByTestId("cut-list-panel"); - // Cut 1 (no bubbles): the lettering choice + "Add speech bubbles" (Manual is default). - const lettering = await screen.findByTestId("lettering-1"); - expect(within(lettering).getByTestId("lettering-mode-manual-1")).toBeChecked(); - expect(screen.getByTestId("add-bubbles-1")).toHaveTextContent("Add speech bubbles"); + // Cut 1 (no bubbles): review opens the focused editor. + expect(await screen.findByTestId("lettering-review-state-1")).toHaveTextContent("Unlettered"); + fireEvent.click(screen.getByTestId("add-bubbles-1")); + expect(await screen.findByTestId("focused-lettering-editor")).toBeInTheDocument(); + expect(screen.getByTestId("ai-draft-current-target")).toHaveTextContent("Cut 01"); - // Switch to AI draft → the copy-prompt CTA appears and copies the lettering prompt. - fireEvent.click(screen.getByTestId("lettering-mode-ai-1")); - fireEvent.click(screen.getByTestId("copy-lettering-1")); + // AI draft is scoped to the focused target. + fireEvent.click(screen.getByTestId("copy-ai-lettering-current")); expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1); const copied = (navigator.clipboard.writeText as ReturnType).mock.calls[0][0] as string; expect(copied).toContain("Draft the speech bubbles and captions for cut 1 of genesis"); expect(copied).toMatch(/do NOT export or upload/i); - // Cut 2 (bubbles already placed): status "Needs review" + a "Review lettering" CTA. + fireEvent.click(screen.getByTestId("cancel-lettering-btn")); + + // Cut 2 (bubbles already placed): status "Needs review" + a draft-saved state. expect(screen.getByTestId("cut-card-status-2")).toHaveTextContent("Needs review"); + expect(screen.getByTestId("lettering-review-state-2")).toHaveTextContent("Draft saved"); expect(screen.getByTestId("add-bubbles-2")).toHaveTextContent("Review lettering"); }); + it("lets a between-scene slot create a focused text-card editor and Save returns to review (#488)", async () => { + let cuts = [ + makeCut({ id: 1, cleanImagePath: "assets/genesis/cut-01-clean.webp" }), + makeCut({ id: 2, cleanImagePath: "assets/genesis/cut-02-clean.webp" }), + ]; + const fn = vi.fn((url: string, opts?: RequestInit) => { + if (url.includes("/asset-diagnostics")) { + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ + diagnostics: cuts.map((c) => ({ cutId: c.id, kind: c.kind === "text" ? "text" : "image", state: c.kind === "text" ? "planned" : "clean-ready", issue: null, convertiblePng: null })), + summary: { planned: 0, needsConversion: 0, missing: 0, cleanReady: 2, finalReady: 0, uploaded: 0 }, + }) }); + } + if (url.includes("/detect-clean-images")) return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ detected: [], stale: [] }) }); + if (url.endsWith("/cuts/genesis") && opts?.method === "PUT") { + cuts = JSON.parse(opts.body as string).cuts; + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ ok: true }) }); + } + if (url.includes("/cuts/genesis")) return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ version: 1, plotFile: "genesis", cuts }) }); + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) }); + }); + render(); + + fireEvent.click(await screen.findByTestId("add-between-scene-1")); + expect(await screen.findByTestId("focused-lettering-editor")).toBeInTheDocument(); + expect(screen.getByTestId("focused-lettering-editor")).toHaveTextContent("Between-scene card 3"); + + fireEvent.click(screen.getByTestId("add-narration")); + fireEvent.click(screen.getByTestId("save-lettering-btn")); + + await waitFor(() => expect(screen.getByTestId("lettering-review-board")).toBeInTheDocument()); + expect(screen.getByTestId("lettering-review-state-3")).toHaveTextContent("Draft saved"); + }); + it("clears the stale diagnostics banner on a file switch whose diagnostics request fails (@re1)", async () => { const fn = vi.fn((url: string) => { if (url.includes("/asset-diagnostics")) { diff --git a/app/web/components/CutListPanel.tsx b/app/web/components/CutListPanel.tsx index 6741a93..be16e20 100644 --- a/app/web/components/CutListPanel.tsx +++ b/app/web/components/CutListPanel.tsx @@ -1,7 +1,7 @@ -import { useState, useEffect, useCallback, useRef } from "react"; +import { Fragment, useState, useEffect, useCallback, useRef } from "react"; import { LetteringEditor } from "./LetteringEditor"; import { AssetImage, assetUrl } from "./asset-image"; -import { buildCodexTaskPrompt, buildLetteringPrompt } from "@app-lib/cartoon-prompt"; +import { buildCodexTaskPrompt } from "@app-lib/cartoon-prompt"; import type { Cut as LibCut } from "@app-lib/cuts"; import { isTextPanel, isStaleTailedExport } from "@app-lib/cuts"; import { withRateLimitRetry, createUploadThrottle, type RetryDeps } from "../lib/upload-retry"; @@ -141,6 +141,25 @@ function boardStatus(cut: Cut, needsConversion: boolean, hasStale: boolean): Boa return { key: "needs-image", label: "Needs image", tone: "muted" }; } +function letteringReviewState(cut: Cut): { label: string; detail: string; tone: BoardTone } { + if (cut.uploadedCid || cut.uploadedUrl) { + return { label: "Complete", detail: "Final image uploaded", tone: "green" }; + } + if (cut.finalImagePath || cut.exportedAt) { + return { label: "Exported", detail: "Ready to upload", tone: "green" }; + } + if ((cut.overlays?.length ?? 0) > 0) { + return { label: "Draft saved", detail: `${cut.overlays.length} overlay${cut.overlays.length === 1 ? "" : "s"} placed`, tone: "amber" }; + } + if (isTextPanel(cut)) { + return { label: "Between-scene card", detail: "Open to add narration or title text", tone: "accent" }; + } + if (cut.cleanImagePath) { + return { label: "Unlettered", detail: "Clean art ready for bubble placement", tone: "muted" }; + } + return { label: "Needs artwork", detail: "Add or sync clean art first", tone: "muted" }; +} + function CutRow({ cut, storyName, @@ -190,10 +209,6 @@ function CutRow({ // generated PNG into this cut without hunting through a hidden folder. const [showCodexPicker, setShowCodexPicker] = useState(false); const [convertingThis, setConvertingThis] = useState(false); - // Lettering is a first-class step (#442): an intentional Manual vs AI-draft - // choice per cut, surfaced on the card (not hidden under Edit). - const [letteringMode, setLetteringMode] = useState<"manual" | "ai">("manual"); - const [letteringCopied, setLetteringCopied] = useState(false); const status = getCutStatus(cut); // A recorded cleanImagePath/finalImagePath whose file is missing/invalid (#302): // surface it precisely rather than letting the field-based status claim the cut @@ -267,18 +282,13 @@ function CutRow({ !isTextPanel(cut) && !!cut.cleanImagePath && !cut.finalImagePath && !cut.uploadedCid && !cut.uploadedUrl && !hasStale && !needsConversion; - const copyLetteringPrompt = useCallback(() => { - navigator.clipboard?.writeText(buildLetteringPrompt(cut as unknown as LibCut, plotFile)); - setLetteringCopied(true); - setTimeout(() => setLetteringCopied(false), 2000); - }, [cut, plotFile]); - const primary: { label: string; onClick: () => void; testid: string } | null = board.key === "convert" ? { label: convertingThis ? "Converting…" : "Convert image", onClick: handleConvertThis, testid: `card-convert-${cut.id}` } : board.key === "review" ? { label: "Review cut", onClick: onOpenEditor, testid: `card-review-${cut.id}` } : board.key === "text" ? { label: "Add captions", onClick: onOpenEditor, testid: `card-letter-${cut.id}` } : board.key === "needs-image" ? { label: "Add artwork", onClick: onToggle, testid: `card-addart-${cut.id}` } : null; // exported / uploaded — the next action is the episode-level upload/publish + const reviewState = letteringReviewState(cut); return (
) : ( -
+
{isTextPanel(cut) ? "Text panel — no artwork needed" : "No artwork yet"}
)} +
+ {reviewState.label} + · {reviewState.detail} +
- {/* Lettering is a first-class, visible step (#442): an intentional - Manual vs AI-draft choice on the card, then the matching CTA. */} - {atLetteringStage && ( -
-
Lettering
- - - {letteringMode === "ai" && ( -

- Paste it to your agent, then review the draft bubbles here and export the final cut. -

- )} -
- )}
{atLetteringStage ? ( - letteringMode === "manual" ? ( - - ) : ( - - ) + ) : primary ? ( +
+ ); +} diff --git a/app/web/components/LetteringEditor.test.tsx b/app/web/components/LetteringEditor.test.tsx index fc22603..a355616 100644 --- a/app/web/components/LetteringEditor.test.tsx +++ b/app/web/components/LetteringEditor.test.tsx @@ -644,7 +644,7 @@ describe("LetteringEditor", () => { expect(screen.getByTestId("inspector-font")).toHaveTextContent("Noto Sans KR"); }); - it("calls onClose when Close button is clicked", () => { + it("calls onClose when Cancel button is clicked", () => { const onClose = vi.fn(); render( { />, ); - fireEvent.click(screen.getByText("Close")); + fireEvent.click(screen.getByText("Cancel")); + expect(onClose).toHaveBeenCalled(); + }); + + it("offers scoped AI draft assistance and can return to review after Save (#488)", async () => { + const onSave = vi.fn().mockResolvedValue(undefined); + const onClose = vi.fn(); + Object.assign(navigator, { clipboard: { writeText: vi.fn() } }); + render( + , + ); + + expect(screen.getByTestId("focused-lettering-editor")).toHaveTextContent("Focused lettering editor"); + fireEvent.click(screen.getByTestId("copy-ai-lettering-current")); + expect(navigator.clipboard.writeText).toHaveBeenCalledWith(expect.stringContaining("cut 1 of plot-01")); + + fireEvent.click(screen.getByTestId("add-speech")); + fireEvent.click(screen.getByTestId("save-lettering-btn")); + await waitFor(() => expect(onSave).toHaveBeenCalled()); expect(onClose).toHaveBeenCalled(); }); diff --git a/app/web/components/LetteringEditor.tsx b/app/web/components/LetteringEditor.tsx index b5bdb1f..e99fc2c 100644 --- a/app/web/components/LetteringEditor.tsx +++ b/app/web/components/LetteringEditor.tsx @@ -22,6 +22,8 @@ import { import { layoutBubbleText } from "@app-lib/bubble-text"; import { cutLetteringChecklist, cutScriptLines, isExportStale, overlaysSignature, type ScriptLine } from "@app-lib/lettering-status"; import { textPanelDimensions } from "@app-lib/cuts"; +import { buildLetteringPrompt } from "@app-lib/cartoon-prompt"; +import type { Cut as LibCut } from "@app-lib/cuts"; import { useAuthedAsset } from "./asset-image"; function toPixel(norm: number, size: number): number { @@ -72,6 +74,10 @@ interface LetteringEditorProps { onExported?: () => void; language?: string; authFetch: (url: string, opts?: RequestInit) => Promise; + /** Focused-editor header label supplied by the review board (#488). */ + targetLabel?: string; + /** When true, the Save button returns to the review board after persisting. */ + returnOnSave?: boolean; } const TYPE_LABEL: Record = { @@ -106,7 +112,7 @@ function clamp(v: number, min: number, max: number): number { return Math.min(max, Math.max(min, v)); } -export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onExported, language = "English", authFetch }: LetteringEditorProps) { +export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onExported, language = "English", authFetch, targetLabel, returnOnSave = false }: LetteringEditorProps) { const bodyFont = getDefaultFont(language); const displayFont = getDisplayFont(); const bodyFontFamily = getFontFamily(bodyFont); @@ -176,6 +182,8 @@ export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onE const [confirmDelete, setConfirmDelete] = useState(false); const [exporting, setExporting] = useState(false); const [exportError, setExportError] = useState(null); + const [saveError, setSaveError] = useState(null); + const [aiCopied, setAiCopied] = useState(false); const [imageBounds, setImageBounds] = useState({ x: 0, y: 0, width: 0, height: 0 }); const containerRef = useRef(null); const imgRef = useRef(null); @@ -355,9 +363,21 @@ export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onE }; }, [imageBounds, updateOverlay]); - const handleSave = useCallback(() => { - onSave(overlays); - }, [overlays, onSave]); + const handleSave = useCallback(async () => { + setSaveError(null); + try { + await onSave(overlays); + if (returnOnSave) onClose(); + } catch (err) { + setSaveError(err instanceof Error ? err.message : "Failed to save overlays"); + } + }, [overlays, onSave, onClose, returnOnSave]); + + const copyAiDraftPrompt = useCallback(() => { + navigator.clipboard?.writeText(buildLetteringPrompt(cut as unknown as LibCut, plotFile)); + setAiCopied(true); + setTimeout(() => setAiCopied(false), 2000); + }, [cut, plotFile]); const handleExport = useCallback(async () => { // Block export when the cut plan contained overlays that could not be placed @@ -515,25 +535,32 @@ export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onE } return ( -
+
{/* Toolbar */} -
-
- Cut #{cut.id} +
+
+
+ Focused lettering editor + {targetLabel ?? `Cut #${cut.id}`} +
+

+ Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review. +

{overlays.length} overlays +
+
-
-
{exportError && {exportError}} + {saveError && {saveError}} - - + +
@@ -635,7 +662,7 @@ export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onE
@@ -830,7 +857,21 @@ export function LetteringEditor({ storyName, cut, plotFile, onSave, onClose, onE
{/* Inspector panel */} -
+
+
+

AI draft assist

+

+ Copy a prompt scoped to {targetLabel ?? `cut ${cut.id}`}. Review and edit any drafted bubbles here before saving. +

+ +
{/* Insert-from-script (#336): drop the cut's planned dialogue/narration/ SFX straight into a prefilled overlay — no copy/paste out of JSON. */} {scriptLines.length > 0 && ( diff --git a/app/web/dist/assets/export-cut-DAQ_YjPc.js b/app/web/dist/assets/export-cut-BdY0Az65.js similarity index 98% rename from app/web/dist/assets/export-cut-DAQ_YjPc.js rename to app/web/dist/assets/export-cut-BdY0Az65.js index a8d1517..19b5b2a 100644 --- a/app/web/dist/assets/export-cut-DAQ_YjPc.js +++ b/app/web/dist/assets/export-cut-BdY0Az65.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-B066-0l8.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; +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-Mt6kwRka.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-B066-0l8.js b/app/web/dist/assets/index-B066-0l8.js deleted file mode 100644 index acf3c0f..0000000 --- a/app/web/dist/assets/index-B066-0l8.js +++ /dev/null @@ -1,143 +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 Du(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qd={exports:{}},to={};/** - * @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 X_;function eC(){if(X_)return to;X_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return to.Fragment=t,to.jsx=i,to.jsxs=i,to}var Z_;function tC(){return Z_||(Z_=1,qd.exports=eC()),qd.exports}var f=tC(),Wd={exports:{}},et={};/** - * @license React - * react.production.js - * - * 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 Q_;function iC(){if(Q_)return et;Q_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(R){return R===null||typeof R!="object"?null:(R=b&&R[b]||R["@@iterator"],typeof R=="function"?R:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,A={};function E(R,Y,C){this.props=R,this.context=Y,this.refs=A,this.updater=C||y}E.prototype.isReactComponent={},E.prototype.setState=function(R,Y){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,Y,"setState")},E.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function D(){}D.prototype=E.prototype;function P(R,Y,C){this.props=R,this.context=Y,this.refs=A,this.updater=C||y}var J=P.prototype=new D;J.constructor=P,N(J,E.prototype),J.isPureReactComponent=!0;var q=Array.isArray;function L(){}var Z={H:null,A:null,T:null,S:null},he=Object.prototype.hasOwnProperty;function ye(R,Y,C){var se=C.ref;return{$$typeof:e,type:R,key:Y,ref:se!==void 0?se:null,props:C}}function U(R,Y){return ye(R.type,Y,R.props)}function re(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function W(R){var Y={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(C){return Y[C]})}var G=/\/+/g;function X(R,Y){return typeof R=="object"&&R!==null&&R.key!=null?W(""+R.key):Y.toString(36)}function I(R){switch(R.status){case"fulfilled":return R.value;case"rejected":throw R.reason;default:switch(typeof R.status=="string"?R.then(L,L):(R.status="pending",R.then(function(Y){R.status==="pending"&&(R.status="fulfilled",R.value=Y)},function(Y){R.status==="pending"&&(R.status="rejected",R.reason=Y)})),R.status){case"fulfilled":return R.value;case"rejected":throw R.reason}}throw R}function j(R,Y,C,se,te){var oe=typeof R;(oe==="undefined"||oe==="boolean")&&(R=null);var $=!1;if(R===null)$=!0;else switch(oe){case"bigint":case"string":case"number":$=!0;break;case"object":switch(R.$$typeof){case e:case t:$=!0;break;case _:return $=R._init,j($(R._payload),Y,C,se,te)}}if($)return te=te(R),$=se===""?"."+X(R,0):se,q(te)?(C="",$!=null&&(C=$.replace(G,"$&/")+"/"),j(te,Y,C,"",function(De){return De})):te!=null&&(re(te)&&(te=U(te,C+(te.key==null||R&&R.key===te.key?"":(""+te.key).replace(G,"$&/")+"/")+$)),Y.push(te)),1;$=0;var ue=se===""?".":se+":";if(q(R))for(var be=0;be>>1,T=j[xe];if(0>>1;xea(C,B))sea(te,C)?(j[xe]=te,j[se]=B,xe=se):(j[xe]=C,j[Y]=B,xe=Y);else if(sea(te,B))j[xe]=te,j[se]=B,xe=se;else break e}}return O}function a(j,O){var B=j.sortIndex-O.sortIndex;return B!==0?B:j.id-O.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],d=[],_=1,x=null,b=3,v=!1,y=!1,N=!1,A=!1,E=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function J(j){for(var O=i(d);O!==null;){if(O.callback===null)s(d);else if(O.startTime<=j)s(d),O.sortIndex=O.expirationTime,t(p,O);else break;O=i(d)}}function q(j){if(N=!1,J(j),!y)if(i(p)!==null)y=!0,L||(L=!0,W());else{var O=i(d);O!==null&&I(q,O.startTime-j)}}var L=!1,Z=-1,he=5,ye=-1;function U(){return A?!0:!(e.unstable_now()-yej&&U());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var T=xe(x.expirationTime<=j);if(j=e.unstable_now(),typeof T=="function"){x.callback=T,J(j),O=!0;break t}x===i(p)&&s(p),J(j)}else s(p);x=i(p)}if(x!==null)O=!0;else{var R=i(d);R!==null&&I(q,R.startTime-j),O=!1}}break e}finally{x=null,b=B,v=!1}O=void 0}}finally{O?W():L=!1}}}var W;if(typeof P=="function")W=function(){P(re)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,X=G.port2;G.port1.onmessage=re,W=function(){X.postMessage(null)}}else W=function(){E(re,0)};function I(j,O){Z=E(function(){j(e.unstable_now())},O)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(j){j.callback=null},e.unstable_forceFrameRate=function(j){0>j||125xe?(j.sortIndex=B,t(d,j),i(p)===null&&j===i(d)&&(N?(D(Z),Z=-1):N=!0,I(q,B-xe))):(j.sortIndex=T,t(p,j),y||v||(y=!0,L||(L=!0,W()))),j},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(j){var O=b;return function(){var B=b;b=O;try{return j.apply(this,arguments)}finally{b=B}}}})(Kd)),Kd}var tb;function sC(){return tb||(tb=1,Yd.exports=rC()),Yd.exports}var Vd={exports:{}},Ji={};/** - * @license React - * react-dom.production.js - * - * 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 aC(){if(ib)return Ji;ib=1;var e=Op();function t(p){var d="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vd.exports=aC(),Vd.exports}/** - * @license React - * react-dom-client.production.js - * - * 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 oC(){if(rb)return io;rb=1;var e=sC(),t=Op(),i=lC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=xe[T],xe[T]=null,T--)}function C(n,r){T++,xe[T]=n.current,n.current=r}var se=R(null),te=R(null),oe=R(null),$=R(null);function ue(n,r){switch(C(oe,r),C(te,n),C(se,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?b_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=b_(r),n=v_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}Y(se),C(se,n)}function be(){Y(se),Y(te),Y(oe)}function De(n){n.memoizedState!==null&&C($,n);var r=se.current,l=v_(r,n.type);r!==l&&(C(te,n),C(se,l))}function Ee(n){te.current===n&&(Y(se),Y(te)),$.current===n&&(Y($),Zl._currentValue=B)}var Be,je;function Ze(n){if(Be===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Be=r&&r[1]||"",je=-1)":-1m||M[u]!==V[m]){var le=` -`+M[u].replace(" at new "," at ");return n.displayName&&le.includes("")&&(le=le.replace("",n.displayName)),le}while(1<=u&&0<=m);break}}}finally{Ce=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ze(l):""}function pt(n,r){switch(n.tag){case 26:case 27:case 5:return Ze(n.type);case 16:return Ze("Lazy");case 13:return n.child!==r&&r!==null?Ze("Suspense Fallback"):Ze("Suspense");case 19:return Ze("SuspenseList");case 0:case 15:return tt(n.type,!1);case 11:return tt(n.type.render,!1);case 1:return tt(n.type,!0);case 31:return Ze("Activity");default:return""}}function Ge(n){try{var r="",l=null;do r+=pt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` -Error generating stack: `+u.message+` -`+u.stack}}var Ae=Object.prototype.hasOwnProperty,Ve=e.unstable_scheduleCallback,At=e.unstable_cancelCallback,Ot=e.unstable_shouldYield,ci=e.unstable_requestPaint,St=e.unstable_now,fi=e.unstable_getCurrentPriorityLevel,ne=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Pe=e.unstable_NormalPriority,Fe=e.unstable_LowPriority,Qe=e.unstable_IdlePriority,H=e.log,ge=e.unstable_setDisableYieldValue,Te=null,me=null;function He(n){if(typeof H=="function"&&ge(n),me&&typeof me.setStrictMode=="function")try{me.setStrictMode(Te,n)}catch{}}var Le=Math.clz32?Math.clz32:Mt,ht=Math.log,it=Math.LN2;function Mt(n){return n>>>=0,n===0?32:31-(ht(n)/it|0)|0}var Dt=256,pi=262144,kt=4194304;function ki(n){var r=n&42;if(r!==0)return r;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function mi(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,S=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=ki(u):(S&=k,S!==0?m=ki(S):l||(l=k&~n,l!==0&&(m=ki(l))))):(k=u&~g,k!==0?m=ki(k):S!==0?m=ki(S):l||(l=u&~n,l!==0&&(m=ki(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function Gt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function mn(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function de(){var n=kt;return kt<<=1,(kt&62914560)===0&&(kt=4194304),n}function Re(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function We(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function st(n,r,l,u,m,g){var S=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,M=n.expirationTimes,V=n.hiddenUpdates;for(l=S&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var da=/[\n"\\]/g;function Ei(n){return n.replace(da,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function fa(n,r,l,u,m,g,S,k){n.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?n.type=S:n.removeAttribute("type"),r!=null?S==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Xi(r)):n.value!==""+Xi(r)&&(n.value=""+Xi(r)):S!=="submit"&&S!=="reset"||n.removeAttribute("value"),r!=null?ma(n,S,Xi(r)):l!=null?ma(n,S,Xi(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+Xi(k):n.removeAttribute("name")}function pa(n,r,l,u,m,g,S,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){lr(n);return}l=l!=null?""+Xi(l):"",r=r!=null?""+Xi(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(n.name=S),lr(n)}function ma(n,r,l){r==="number"&&an(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Wn(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),xi=!1;if(Et)try{var Rn={};Object.defineProperty(Rn,"passive",{get:function(){xi=!0}}),window.addEventListener("test",Rn,Rn),window.removeEventListener("test",Rn,Rn)}catch{xi=!1}var on=null,cr=null,Ls=null;function vm(){if(Ls)return Ls;var n,r=cr,l=r.length,u,m="value"in on?on.value:on.textContent,g=m.length;for(n=0;n=_l),Em=" ",Nm=!1;function Tm(n,r){switch(n){case"keyup":return S1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var ba=!1;function C1(n,r){switch(n){case"compositionend":return jm(r);case"keypress":return r.which!==32?null:(Nm=!0,Em);case"textInput":return n=r.data,n===Em&&Nm?null:n;default:return null}}function k1(n,r){if(ba)return n==="compositionend"||!Xu&&Tm(n,r)?(n=vm(),Ls=cr=on=null,ba=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=zm(l)}}function Im(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Im(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Hm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=an(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=an(n.document)}return r}function Ju(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var D1=Et&&"documentMode"in document&&11>=document.documentMode,va=null,eh=null,Sl=null,th=!1;function Um(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;th||va==null||va!==an(u)||(u=va,"selectionStart"in u&&Ju(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Sl&&yl(Sl,u)||(Sl=u,u=Dc(eh,"onSelect"),0>=S,m-=S,gr=1<<32-Le(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var Tt=Q(F,Ie,K[lt],ce);if(Tt===null){Ie===null&&(Ie=vt);break}n&&Ie&&Tt.alternate===null&&r(F,Ie),z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt,Ie=vt}if(lt===K.length)return l(F,Ie),yt&&Dr(F,lt),Ue;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Cs=Q(F,Ie,Tt.value,ce);if(Cs===null){Ie===null&&(Ie=vt);break}n&&Ie&&Cs.alternate===null&&r(F,Ie),z=g(Cs,z,lt),Nt===null?Ue=Cs:Nt.sibling=Cs,Nt=Cs,Ie=vt}if(Tt.done)return l(F,Ie),yt&&Dr(F,lt),Ue;if(Ie===null){for(;!Tt.done;lt++,Tt=K.next())Tt=fe(F,Tt.value,ce),Tt!==null&&(z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt);return yt&&Dr(F,lt),Ue}for(Ie=u(Ie);!Tt.done;lt++,Tt=K.next())Tt=ie(Ie,F,lt,Tt.value,ce),Tt!==null&&(n&&Tt.alternate!==null&&Ie.delete(Tt.key===null?lt:Tt.key),z=g(Tt,z,lt),Nt===null?Ue=Tt:Nt.sibling=Tt,Nt=Tt);return n&&Ie.forEach(function(Jw){return r(F,Jw)}),yt&&Dr(F,lt),Ue}function Ht(F,z,K,ce){if(typeof K=="object"&&K!==null&&K.type===N&&K.key===null&&(K=K.props.children),typeof K=="object"&&K!==null){switch(K.$$typeof){case v:e:{for(var Ue=K.key;z!==null;){if(z.key===Ue){if(Ue=K.type,Ue===N){if(z.tag===7){l(F,z.sibling),ce=m(z,K.props.children),ce.return=F,F=ce;break e}}else if(z.elementType===Ue||typeof Ue=="object"&&Ue!==null&&Ue.$$typeof===he&&Ws(Ue)===z.type){l(F,z.sibling),ce=m(z,K.props),Tl(ce,K),ce.return=F,F=ce;break e}l(F,z);break}else r(F,z);z=z.sibling}K.type===N?(ce=Hs(K.props.children,F.mode,ce,K.key),ce.return=F,F=ce):(ce=Xo(K.type,K.key,K.props,null,F.mode,ce),Tl(ce,K),ce.return=F,F=ce)}return S(F);case y:e:{for(Ue=K.key;z!==null;){if(z.key===Ue)if(z.tag===4&&z.stateNode.containerInfo===K.containerInfo&&z.stateNode.implementation===K.implementation){l(F,z.sibling),ce=m(z,K.children||[]),ce.return=F,F=ce;break e}else{l(F,z);break}else r(F,z);z=z.sibling}ce=oh(K,F.mode,ce),ce.return=F,F=ce}return S(F);case he:return K=Ws(K),Ht(F,z,K,ce)}if(I(K))return Oe(F,z,K,ce);if(W(K)){if(Ue=W(K),typeof Ue!="function")throw Error(s(150));return K=Ue.call(K),qe(F,z,K,ce)}if(typeof K.then=="function")return Ht(F,z,nc(K),ce);if(K.$$typeof===P)return Ht(F,z,Jo(F,K),ce);rc(F,K)}return typeof K=="string"&&K!==""||typeof K=="number"||typeof K=="bigint"?(K=""+K,z!==null&&z.tag===6?(l(F,z.sibling),ce=m(z,K),ce.return=F,F=ce):(l(F,z),ce=lh(K,F.mode,ce),ce.return=F,F=ce),S(F)):l(F,z)}return function(F,z,K,ce){try{Nl=0;var Ue=Ht(F,z,K,ce);return Ra=null,Ue}catch(Ie){if(Ie===Aa||Ie===tc)throw Ie;var Nt=Dn(29,Ie,null,F.mode);return Nt.lanes=ce,Nt.return=F,Nt}finally{}}}var Ys=ug(!0),hg=ug(!1),ls=!1;function vh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function yh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function os(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function cs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(jt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=Vo(n),Km(n,null,l),r}return Ko(n,u,r,l),Vo(n)}function jl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ct(n,l)}}function Sh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=S:g=g.next=S,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var wh=!1;function Al(){if(wh){var n=ja;if(n!==null)throw n}}function Rl(n,r,l,u){wh=!1;var m=n.updateQueue;ls=!1;var g=m.firstBaseUpdate,S=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var M=k,V=M.next;M.next=null,S===null?g=V:S.next=V,S=M;var le=n.alternate;le!==null&&(le=le.updateQueue,k=le.lastBaseUpdate,k!==S&&(k===null?le.firstBaseUpdate=V:k.next=V,le.lastBaseUpdate=M))}if(g!==null){var fe=m.baseState;S=0,le=V=M=null,k=g;do{var Q=k.lane&-536870913,ie=Q!==k.lane;if(ie?(bt&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ta&&(wh=!0),le!==null&&(le=le.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=n,qe=k;Q=r;var Ht=l;switch(qe.tag){case 1:if(Oe=qe.payload,typeof Oe=="function"){fe=Oe.call(Ht,fe,Q);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=qe.payload,Q=typeof Oe=="function"?Oe.call(Ht,fe,Q):Oe,Q==null)break e;fe=x({},fe,Q);break e;case 2:ls=!0}}Q=k.callback,Q!==null&&(n.flags|=64,ie&&(n.flags|=8192),ie=m.callbacks,ie===null?m.callbacks=[Q]:ie.push(Q))}else ie={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},le===null?(V=le=ie,M=fe):le=le.next=ie,S|=Q;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ie=k,k=ie.next,ie.next=null,m.lastBaseUpdate=ie,m.shared.pending=null}}while(!0);le===null&&(M=fe),m.baseState=M,m.firstBaseUpdate=V,m.lastBaseUpdate=le,g===null&&(m.shared.lanes=0),ps|=S,n.lanes=S,n.memoizedState=fe}}function dg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function fg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var S=j.T,k={};j.T=k,$h(n,!1,r,l);try{var M=m(),V=j.S;if(V!==null&&V(k,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var le=$1(M,u);Bl(n,r,le,Pn(n))}else Bl(n,r,u,Pn(n))}catch(fe){Bl(n,r,{then:function(){},status:"rejected",reason:fe},Pn())}finally{O.p=g,S!==null&&k.types!==null&&(S.types=k.types),j.T=S}}function K1(){}function Hh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Wg(n).queue;qg(n,m,r,B,l===null?K1:function(){return Gg(n),l(u)})}function Wg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:B,baseState:B,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:B},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Gg(n){var r=Wg(n);r.next===null&&(r=n.alternate.memoizedState),Bl(n,r.next.queue,{},Pn())}function Uh(){return qi(Zl)}function Yg(){return hi().memoizedState}function Kg(){return hi().memoizedState}function V1(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Pn();n=os(l);var u=cs(r,n,l);u!==null&&(wn(u,r,l),jl(u,r,l)),r={cache:gh()},n.payload=r;return}r=r.return}}function X1(n,r,l){var u=Pn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pc(n)?Xg(r,l):(l=sh(n,r,l,u),l!==null&&(wn(l,n,u),Zg(l,r,u)))}function Vg(n,r,l){var u=Pn();Bl(n,r,l,u)}function Bl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(pc(n))Xg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var S=r.lastRenderedState,k=g(S,l);if(m.hasEagerState=!0,m.eagerState=k,Mn(k,S))return Ko(n,r,m,0),$t===null&&Yo(),!1}catch{}finally{}if(l=sh(n,r,m,u),l!==null)return wn(l,n,u),Zg(l,r,u),!0}return!1}function $h(n,r,l,u){if(u={lane:2,revertLane:vd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},pc(n)){if(r)throw Error(s(479))}else r=sh(n,l,u,2),r!==null&&wn(r,n,2)}function pc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function Xg(n,r){Da=lc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function Zg(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ct(n,l)}}var Ll={readContext:qi,use:uc,useCallback:ri,useContext:ri,useEffect:ri,useImperativeHandle:ri,useLayoutEffect:ri,useInsertionEffect:ri,useMemo:ri,useReducer:ri,useRef:ri,useState:ri,useDebugValue:ri,useDeferredValue:ri,useTransition:ri,useSyncExternalStore:ri,useId:ri,useHostTransitionStatus:ri,useFormState:ri,useActionState:ri,useOptimistic:ri,useMemoCache:ri,useCacheRefresh:ri};Ll.useEffectEvent=ri;var Qg={readContext:qi,use:uc,useCallback:function(n,r){return cn().memoizedState=[n,r===void 0?null:r],n},useContext:qi,useEffect:Lg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,dc(4194308,4,Ig.bind(null,r,n),l)},useLayoutEffect:function(n,r){return dc(4194308,4,n,r)},useInsertionEffect:function(n,r){dc(4,2,n,r)},useMemo:function(n,r){var l=cn();r=r===void 0?null:r;var u=n();if(Ks){He(!0);try{n()}finally{He(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=cn();if(l!==void 0){var m=l(r);if(Ks){He(!0);try{l(r)}finally{He(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=X1.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=cn();return n={current:n},r.memoizedState=n},useState:function(n){n=Lh(n);var r=n.queue,l=Vg.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Ph,useDeferredValue:function(n,r){var l=cn();return Ih(l,n,r)},useTransition:function(){var n=Lh(!1);return n=qg.bind(null,rt,n.queue,!0,!1),cn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=cn();if(yt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),$t===null)throw Error(s(349));(bt&127)!==0||bg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Lg(yg.bind(null,u,g,n),[n]),u.flags|=2048,La(9,{destroy:void 0},vg.bind(null,u,g,l,r),null),l},useId:function(){var n=cn(),r=$t.identifierPrefix;if(yt){var l=xr,u=gr;l=(u&~(1<<32-Le(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=oc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}g[ut]=r,g[at]=u;e:for(S=r.child;S!==null;){if(S.tag===5||S.tag===6)g.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===r)break e;for(;S.sibling===null;){if(S.return===null||S.return===r)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}r.stateNode=g;e:switch(Gi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ir(r)}}return Vt(r),id(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Ir(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ea(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Fi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[ut]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||x_(n.nodeValue,l)),n||ss(r,!0)}else n=Bc(n).createTextNode(u),n[ut]=r,r.stateNode=n}return Vt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ea(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[ut]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Vt(r),n=!1}else l=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Ln(r),r):(Ln(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Vt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ea(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[ut]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Vt(r),m=!1}else m=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Ln(r),r):(Ln(r),null)}return Ln(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),bc(r,r.updateQueue),Vt(r),null);case 4:return be(),n===null&&Cd(r.stateNode.containerInfo),Vt(r),null;case 10:return Lr(r.type),Vt(r),null;case 19:if(Y(ui),u=r.memoizedState,u===null)return Vt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)zl(u,!1);else{if(si!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=ac(n),g!==null){for(r.flags|=128,zl(u,!1),n=g.updateQueue,r.updateQueue=n,bc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Vm(l,n),l=l.sibling;return C(ui,ui.current&1|2),yt&&Dr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&St()>Cc&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304)}else{if(!m)if(n=ac(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,bc(r,n),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!yt)return Vt(r),null}else 2*St()-u.renderingStartTime>Cc&&l!==536870912&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=St(),n.sibling=null,l=ui.current,C(ui,m?l&1|2:l&1),yt&&Dr(r,u.treeForkCount),n):(Vt(r),null);case 22:case 23:return Ln(r),kh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Vt(r),r.subtreeFlags&6&&(r.flags|=8192)):Vt(r),l=r.updateQueue,l!==null&&bc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&Y(qs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Lr(_i),Vt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function tw(n,r){switch(uh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Lr(_i),be(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Ee(r),null;case 31:if(r.memoizedState!==null){if(Ln(r),r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Ln(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return Y(ui),null;case 4:return be(),null;case 10:return Lr(r.type),null;case 22:case 23:return Ln(r),kh(),n!==null&&Y(qs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Lr(_i),null;case 25:return null;default:return null}}function Sx(n,r){switch(uh(r),r.tag){case 3:Lr(_i),be();break;case 26:case 27:case 5:Ee(r);break;case 4:be();break;case 31:r.memoizedState!==null&&Ln(r);break;case 13:Ln(r);break;case 19:Y(ui);break;case 10:Lr(r.type);break;case 22:case 23:Ln(r),kh(),n!==null&&Y(qs);break;case 24:Lr(_i)}}function Pl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,S=l.inst;u=g(),S.destroy=u}l=l.next}while(l!==m)}}catch(k){Lt(r,r.return,k)}}function ds(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var S=u.inst,k=S.destroy;if(k!==void 0){S.destroy=void 0,m=r;var M=l,V=k;try{V()}catch(le){Lt(m,M,le)}}}u=u.next}while(u!==g)}}catch(le){Lt(r,r.return,le)}}function wx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{fg(r,l)}catch(u){Lt(n,n.return,u)}}}function Cx(n,r,l){l.props=Vs(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Lt(n,r,u)}}function Il(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Lt(n,r,m)}}function _r(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Lt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Lt(n,r,m)}else l.current=null}function kx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Lt(n,n.return,m)}}function nd(n,r,l){try{var u=n.stateNode;ww(u,n.type,l,r),u[at]=r}catch(m){Lt(n,n.return,m)}}function Ex(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&bs(n.type)||n.tag===4}function rd(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Ex(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&bs(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function sd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=ln));else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(sd(n,r,l),n=n.sibling;n!==null;)sd(n,r,l),n=n.sibling}function vc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(vc(n,r,l),n=n.sibling;n!==null;)vc(n,r,l),n=n.sibling}function Nx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Gi(r,u,l),r[ut]=n,r[at]=l}catch(g){Lt(n,n.return,g)}}var Hr=!1,yi=!1,ad=!1,Tx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function iw(n,r){if(n=n.containerInfo,Nd=Uc,n=Hm(n),Ju(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var S=0,k=-1,M=-1,V=0,le=0,fe=n,Q=null;t:for(;;){for(var ie;fe!==l||m!==0&&fe.nodeType!==3||(k=S+m),fe!==g||u!==0&&fe.nodeType!==3||(M=S+u),fe.nodeType===3&&(S+=fe.nodeValue.length),(ie=fe.firstChild)!==null;)Q=fe,fe=ie;for(;;){if(fe===n)break t;if(Q===l&&++V===m&&(k=S),Q===g&&++le===u&&(M=S),(ie=fe.nextSibling)!==null)break;fe=Q,Q=fe.parentNode}fe=ie}l=k===-1||M===-1?null:{start:k,end:M}}else l=null}l=l||{start:0,end:0}}else l=null;for(Td={focusedElem:n,selectionRange:l},Uc=!1,Mi=r;Mi!==null;)if(r=Mi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Mi=n;else for(;Mi!==null;){switch(r=Mi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),Gi(g,u,l),g[ut]=n,ti(g),u=g;break e;case"link":var S=B_("link","href",m).get(u+(l.href||""));if(S){for(var k=0;kHt&&(S=Ht,Ht=qe,qe=S);var F=Pm(k,qe),z=Pm(k,Ht);if(F&&z&&(ie.rangeCount!==1||ie.anchorNode!==F.node||ie.anchorOffset!==F.offset||ie.focusNode!==z.node||ie.focusOffset!==z.offset)){var K=fe.createRange();K.setStart(F.node,F.offset),ie.removeAllRanges(),qe>Ht?(ie.addRange(K),ie.extend(z.node,z.offset)):(K.setEnd(z.node,z.offset),ie.addRange(K))}}}}for(fe=[],ie=k;ie=ie.parentNode;)ie.nodeType===1&&fe.push({element:ie,left:ie.scrollLeft,top:ie.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,j.T=null,l=fd,fd=null;var g=gs,S=Wr;if(Ni=0,Ha=gs=null,Wr=0,(jt&6)!==0)throw Error(s(331));var k=jt;if(jt|=4,Ix(g.current),Ox(g,g.current,S,l),jt=k,Wl(0,!1),me&&typeof me.onPostCommitFiberRoot=="function")try{me.onPostCommitFiberRoot(Te,g)}catch{}return!0}finally{O.p=m,j.T=u,n_(n,r)}}function s_(n,r,l){r=Kn(l,r),r=Gh(n.stateNode,r,2),n=cs(n,r,2),n!==null&&(We(n,2),br(n))}function Lt(n,r,l){if(n.tag===3)s_(n,n,l);else for(;r!==null;){if(r.tag===3){s_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ms===null||!ms.has(u))){n=Kn(l,n),l=ax(2),u=cs(r,l,2),u!==null&&(lx(l,u,r,n),We(u,2),br(u));break}}r=r.return}}function xd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new sw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(cd=!0,m.add(l),n=uw.bind(null,n,r,l),r.then(n,n))}function uw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,$t===n&&(bt&l)===l&&(si===4||si===3&&(bt&62914560)===bt&&300>St()-wc?(jt&2)===0&&Ua(n,0):ud|=l,Ia===bt&&(Ia=0)),br(n)}function a_(n,r){r===0&&(r=de()),n=Is(n,r),n!==null&&(We(n,r),br(n))}function hw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),a_(n,l)}function dw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),a_(n,l)}function fw(n,r){return Ve(n,r)}var Ac=null,Fa=null,_d=!1,Rc=!1,bd=!1,_s=0;function br(n){n!==Fa&&n.next===null&&(Fa===null?Ac=Fa=n:Fa=Fa.next=n),Rc=!0,_d||(_d=!0,mw())}function Wl(n,r){if(!bd&&Rc){bd=!0;do for(var l=!1,u=Ac;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var S=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Le(42|n)+1)-1,g&=m&~(S&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,u_(u,g))}else g=bt,g=mi(u,u===$t?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Gt(u,g)||(l=!0,u_(u,g));u=u.next}while(l);bd=!1}}function pw(){l_()}function l_(){Rc=_d=!1;var n=0;_s!==0&&kw()&&(n=_s);for(var r=St(),l=null,u=Ac;u!==null;){var m=u.next,g=o_(u,r);g===0?(u.next=null,l===null?Ac=m:l.next=m,m===null&&(Fa=l)):(l=u,(n!==0||(g&3)!==0)&&(Rc=!0)),u=m}Ni!==0&&Ni!==5||Wl(n),_s!==0&&(_s=0)}function o_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var le=M.transferSize,fe=M.initiatorType;le&&__(fe)&&(M=M.responseEnd,S+=le*(M"u"?null:document;function A_(n,r,l){var u=qa;if(u&&typeof r=="string"&&r){var m=Ei(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),j_.has(m)||(j_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Gi(r,"link",n),ti(r),u.head.appendChild(r)))}}function Bw(n){Gr.D(n),A_("dns-prefetch",n,null)}function Lw(n,r){Gr.C(n,r),A_("preconnect",n,r)}function Ow(n,r,l){Gr.L(n,r,l);var u=qa;if(u&&n&&r){var m='link[rel="preload"][as="'+Ei(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Ei(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Ei(l.imageSizes)+'"]')):m+='[href="'+Ei(n)+'"]';var g=m;switch(r){case"style":g=Wa(n);break;case"script":g=Ga(n)}er.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),er.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(Vl(g))||r==="script"&&u.querySelector(Xl(g))||(r=u.createElement("link"),Gi(r,"link",n),ti(r),u.head.appendChild(r)))}}function zw(n,r){Gr.m(n,r);var l=qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Ei(u)+'"][href="'+Ei(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ga(n)}if(!er.has(g)&&(n=x({rel:"modulepreload",href:n},r),er.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Xl(g)))return}u=l.createElement("link"),Gi(u,"link",n),ti(u),l.head.appendChild(u)}}}function Pw(n,r,l){Gr.S(n,r,l);var u=qa;if(u&&n){var m=Fn(u).hoistableStyles,g=Wa(n);r=r||"default";var S=m.get(g);if(!S){var k={loading:0,preload:null};if(S=u.querySelector(Vl(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Ld(n,l);var M=S=u.createElement("link");ti(M),Gi(M,"link",n),M._p=new Promise(function(V,le){M.onload=V,M.onerror=le}),M.addEventListener("load",function(){k.loading|=1}),M.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Oc(S,r,u)}S={type:"stylesheet",instance:S,count:1,state:k},m.set(g,S)}}}function Iw(n,r){Gr.X(n,r);var l=qa;if(l&&n){var u=Fn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Od(n,r),g=l.createElement("script"),ti(g),Gi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Hw(n,r){Gr.M(n,r);var l=qa;if(l&&n){var u=Fn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Od(n,r),g=l.createElement("script"),ti(g),Gi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function R_(n,r,l,u){var m=(m=oe.current)?Lc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Wa(l.href),l=Fn(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Wa(l.href);var g=Fn(m).hoistableStyles,S=g.get(n);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,S),(g=m.querySelector(Vl(n)))&&!g._p&&(S.instance=g,S.state.loading=5),er.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},er.set(n,l),g||Uw(m,n,l,S.state))),r&&u===null)throw Error(s(528,""));return S}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ga(l),l=Fn(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Wa(n){return'href="'+Ei(n)+'"'}function Vl(n){return'link[rel="stylesheet"]['+n+"]"}function M_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function Uw(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Gi(r,"link",l),ti(r),n.head.appendChild(r))}function Ga(n){return'[src="'+Ei(n)+'"]'}function Xl(n){return"script[async]"+n}function D_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Ei(l.href)+'"]');if(u)return r.instance=u,ti(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),ti(u),Gi(u,"style",m),Oc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Wa(l.href);var g=n.querySelector(Vl(m));if(g)return r.state.loading|=4,r.instance=g,ti(g),g;u=M_(l),(m=er.get(m))&&Ld(u,m),g=(n.ownerDocument||n).createElement("link"),ti(g);var S=g;return S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),Gi(g,"link",u),r.state.loading|=4,Oc(g,l.precedence,n),r.instance=g;case"script":return g=Ga(l.src),(m=n.querySelector(Xl(g)))?(r.instance=m,ti(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Od(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),ti(m),Gi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,Oc(u,l.precedence,n));return r.instance}function Oc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,S=0;S title"):null)}function $w(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function O_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Fw(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Wa(u.href),g=r.querySelector(Vl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Pc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,ti(g);return}g=r.ownerDocument||r,u=M_(u),(m=er.get(m))&&Ld(u,m),g=g.createElement("link"),ti(g);var S=g;S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),Gi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Pc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var zd=0;function qw(n,r){return n.stylesheets&&n.count===0&&Hc(n,n.stylesheets),0zd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Pc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Ic=null;function Hc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Ic=new Map,r.forEach(Ww,n),Ic=null,Pc.call(n))}function Ww(n,r){if(!(r.state.loading&4)){var l=Ic.get(n);if(l)var u=l.get(null);else{l=new Map,Ic.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Gd.exports=oC(),Gd.exports}var uC=cC();const hC=Du(uC);function dC({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const d=await e(t);d&&a(d),c(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsxs("div",{className:"w-full max-w-sm",children:[f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),f.jsxs("form",{onSubmit:h,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&f.jsx("p",{className:"text-error text-xs",children:s}),f.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),f.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function fC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),d=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return f.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:f.jsx("div",{className:"w-full max-w-sm",children:f.jsxs("div",{className:"border-border rounded border p-6",children:[f.jsxs("div",{className:"mb-6 text-center",children:[f.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),f.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),f.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),f.jsxs("form",{onSubmit:d,className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),f.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),f.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&f.jsx("p",{className:"text-error text-xs",children:o}),f.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const Xd="http://localhost:7777";function Sy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[d,_]=w.useState(null),x=w.useCallback((E,D)=>fetch(E,{...D,headers:{...D==null?void 0:D.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Xd}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${Xd}/api/wallet/create`,{method:"POST"}),D=await E.json();if(!E.ok)throw new Error(D.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},y=async E=>{c(E.walletId||E.name),_(null);try{const D=await x(`${Xd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),P=await D.json();if(!D.ok)throw new Error(P.error||"Wallet switch failed");b()}catch(D){_(D instanceof Error?D.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},A=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&f.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),d&&f.jsx("p",{className:"text-error text-xs",children:d}),f.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&f.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>f.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),f.jsx("button",{onClick:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),t&&t.exists&&t.address&&f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),f.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Name"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:A(t.address)}),f.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),f.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC"}),f.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"PLOT"}),f.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Network"}),f.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&f.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[f.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>f.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),f.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&f.jsx("button",{onClick:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),d&&f.jsx("p",{className:"text-error text-xs",children:d})]}),f.jsxs("div",{className:"border-border border-t pt-3",children:[f.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),f.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),f.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&f.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Su(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const zp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function pC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,d]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[y,N]=w.useState("AI Writer"),[A,E]=w.useState(""),[D,P]=w.useState(""),[J,q]=w.useState(!1),[L,Z]=w.useState(null),[he,ye]=w.useState(""),[U,re]=w.useState(null),[W,G]=w.useState(!1),[X,I]=w.useState(null),[j,O]=w.useState(null),[B,xe]=w.useState(null),T=w.useCallback((te,oe)=>fetch(te,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(te=>te.json()).then(te=>v(te)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(te=>te.ok?te.json():null).then(te=>{te&&xe(te)}).catch(()=>{})},[]);const R=async()=>{if(!y.trim()){Z("Agent name is required");return}if(!A.trim()){Z("Description is required");return}q(!0),Z(null);try{const te=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:y,description:A,...D.trim()&&{genre:D}})}),oe=await te.json();if(!te.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(te){Z(te instanceof Error?te.message:"Registration failed")}q(!1)},Y=async()=>{if(!he.trim()||!/^0x[a-fA-F0-9]{40}$/.test(he)){I("Enter a valid wallet address (0x...)");return}G(!0),I(null),re(null);try{const te=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:he})}),oe=await te.json();if(!te.ok)throw new Error(oe.error||"Failed to generate binding code");re(oe)}catch(te){I(te instanceof Error?te.message:"Failed to generate binding code")}G(!1)},C=async(te,oe)=>{await navigator.clipboard.writeText(te),O(oe),setTimeout(()=>O(null),2e3)},se=async()=>{if(h(null),d(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const te=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!te.ok){const oe=await te.json();throw new Error(oe.error||"Reset failed")}d(!0),s(""),o(""),setTimeout(()=>d(!1),3e3)}catch(te){h(te instanceof Error?te.message:"Reset failed")}x(!1)};return f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),f.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&f.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),f.jsx("p",{className:"text-muted text-xs",children:f.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),f.jsx("input",{value:y,onChange:te=>N(te.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),f.jsx("input",{value:A,onChange:te=>E(te.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),f.jsx("input",{value:D,onChange:te=>P(te.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),L&&f.jsx("p",{className:"text-error text-xs",children:L}),f.jsx("button",{onClick:R,disabled:J||!y.trim()||!A.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:J?"Registering...":"Register Agent Identity"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.claude.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.codex.installed?"Installed":"Not detected"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),f.jsx("span",{className:"text-muted text-xs font-mono",children:(B==null?void 0:B.codex.version)??"—"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),f.jsx("span",{className:"text-muted text-xs",children:(B==null?void 0:B.codex.imageGeneration)??"unknown"})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),f.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:B!=null&&B.codex.installed?B.codex.auth==="ok"?"ok":"unclear":"—"})]}),Su(B)&&f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:zp}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),f.jsx("span",{className:"text-muted text-xs",children:B!=null&&B.checkedAt?new Date(B.checkedAt).toLocaleString():"—"})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?f.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",f.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),f.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[f.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),f.jsx("p",{children:'2. Click "Generate Binding Code"'}),f.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),f.jsx("input",{value:he,onChange:te=>ye(te.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),X&&f.jsx("p",{className:"text-error text-xs",children:X}),f.jsx("button",{onClick:Y,disabled:W||!he.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"Generating...":"Generate Binding Code"}),U&&f.jsxs("div",{className:"space-y-3 mt-3",children:[f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.signature}),f.jsx("button",{onClick:()=>C(U.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="signature"?"Copied!":"Copy"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:U.owsWallet}),f.jsx("button",{onClick:()=>C(U.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="wallet"?"Copied!":"Copy"})]})]}),U.agentId&&f.jsxs("div",{children:[f.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:U.agentId}),f.jsx("button",{onClick:()=>C(String(U.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:j==="agentId"?"Copied!":"Copy"})]})]}),f.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),f.jsx(Sy,{token:e}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("input",{type:"password",value:i,onChange:te=>s(te.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),f.jsx("input",{type:"password",value:a,onChange:te=>o(te.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&f.jsx("p",{className:"text-error text-xs",children:c}),p&&f.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),f.jsx("button",{onClick:se,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),f.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const mC="http://localhost:7777";function gC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${mC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?f.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[f.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),f.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),f.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[f.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),f.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),f.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Active wallet"}),f.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Address"}),f.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"ETH Balance"}),f.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"USDC Balance"}),f.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),f.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Royalties earned"}),f.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),f.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),f.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[f.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),f.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),f.jsxs("div",{className:"flex justify-between text-xs",children:[f.jsx("span",{className:"text-muted",children:"Stories published"}),f.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),f.jsxs("div",{className:"border-border rounded border p-4",children:[f.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?f.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):f.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>f.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[f.jsxs("div",{className:"flex items-start justify-between",children:[f.jsxs("div",{children:[h.genre&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),f.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),f.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&f.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),f.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),f.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),f.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),f.jsxs("div",{className:"rounded bg-background p-1.5",children:[f.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),f.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),f.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>f.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),f.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&f.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),f.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[f.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&f.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&f.jsx("div",{className:"border-border rounded border p-4",children:f.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):f.jsx("div",{className:"flex h-full items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const xC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},_C={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function bC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,d]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),y=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const L=await q.json();h(L.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const L=await q.json();d(L.stories)}}catch{}},[e]),A=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),y())}catch{}},[e,N,y]);w.useEffect(()=>{y();const q=setInterval(y,5e3);return()=>clearInterval(q)},[y]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(L=>{const Z=new Set(L);return Z.has(q)?Z.delete(q):Z.add(q),Z})},D=q=>{var Z;const L=q.map(he=>{var ye;return{file:he.file,num:(ye=he.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(he=>he.num!=null).sort((he,ye)=>parseInt(ye.num)-parseInt(he.num));return L.length>0?L[0].file:q.some(he=>he.file==="genesis.md")?"genesis.md":q.some(he=>he.file==="structure.md")?"structure.md":((Z=q[0])==null?void 0:Z.file)??null},P=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const L=D(q.files);L&&s(q.name,L)}},J=q=>{const L=Z=>{if(Z==="structure.md")return 0;if(Z==="genesis.md")return 1;const he=Z.match(/^plot-(\d+)\.md$/);return he?2+parseInt(he[1]):100};return[...q].sort((Z,he)=>L(Z.file)-L(he.file))};return b?f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),f.jsx("span",{className:"text-xs text-muted",children:p.length})]}),f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[f.jsx("span",{children:"←"}),f.jsx("span",{children:"Back"})]})}),f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?f.jsx("div",{className:"p-3 text-sm text-muted",children:f.jsx("p",{children:"No archived stories."})}):p.map(q=>f.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[f.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),f.jsx("button",{onClick:()=>A(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),f.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&f.jsx("div",{className:"px-3 py-2 border-b border-border",children:f.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[f.jsx("span",{children:"+"}),f.jsx("span",{children:"New Story"})]})}),f.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>f.jsx("div",{children:f.jsxs("button",{onClick:()=>s(q,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===q?"bg-surface":""}`,children:[f.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),f.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?f.jsxs("div",{className:"p-3 text-sm text-muted",children:[f.jsx("p",{children:"No stories yet."}),f.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>f.jsxs("div",{children:[f.jsxs("button",{onClick:()=>P(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[f.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),f.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&f.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),f.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&f.jsx("div",{className:"pl-4",children:J(q.files).map(L=>{const Z=t===q.name&&i===L.file;return f.jsxs("button",{onClick:()=>s(q.name,L.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${Z?"bg-surface font-medium":""}`,children:[f.jsx("span",{className:_C[L.status],children:xC[L.status]}),f.jsx("span",{className:"truncate font-mono",children:L.file})]},L.file)})})]},q.name))]}),f.jsx("div",{className:"px-3 py-2 border-t border-border",children:f.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:f.jsx("span",{children:"Archives"})})})]})}/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * 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 wy=Object.defineProperty,vC=Object.getOwnPropertyDescriptor,yC=(e,t)=>{for(var i in t)wy(e,i,{get:t[i],enumerable:!0})},oi=(e,t,i,s)=>{for(var a=s>1?void 0:s?vC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&wy(t,i,a),a},Me=(e,t)=>(i,s)=>t(i,s,e),ab="Terminal input",zf={get:()=>ab,set:e=>ab=e},lb="Too much output to announce, navigate to rows manually to read",Pf={get:()=>lb,set:e=>lb=e};function SC(e){return e.replace(/\r?\n/g,"\r")}function wC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function CC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function kC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Cy(a,t,i,s)}}function Cy(e,t,i,s){e=SC(e),e=wC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function ky(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function ob(e,t,i,s,a){ky(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function js(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Bu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var EC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},NC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,d=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let y=0,N;for(;(N=this.interim[++y]&63)&&y<4;)v<<=6,v|=N;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=A-y;for(;d=i)return 0;if(N=e[d++],(N&192)!==128){d--,b=!0;break}else this.interim[y++]=N,v<<=6,v|=N&63}b||(A===2?v<128?d--:t[s++]=v:A===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=d;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Ey="",Rs=" ",Ao=class Ny{constructor(){this.fg=0,this.bg=0,this.extended=new wu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Ny;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},wu=class Ty{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Ty(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class jy extends Ao{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wu,this.combinedData=""}static fromCharData(t){let i=new jy;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?js(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},cb="di$target",If="di$dependencies",Zd=new Map;function TC(e){return e[If]||[]}function Ui(e){if(Zd.has(e))return Zd.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");jC(t,i,a)};return t._id=e,Zd.set(e,t),t}function jC(e,t,i){t[cb]===t?t[If].push({id:e,index:i}):(t[If]=[{id:e,index:i}],t[cb]=t)}var fn=Ui("BufferService"),Ay=Ui("CoreMouseService"),ca=Ui("CoreService"),AC=Ui("CharsetService"),Pp=Ui("InstantiationService"),Ry=Ui("LogService"),pn=Ui("OptionsService"),My=Ui("OscLinkService"),RC=Ui("UnicodeService"),Ro=Ui("DecorationService"),Hf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,d=!1;for(let x=0;xa?a.activate(N,A,v):MC(N,A),hover:(N,A)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,A,v)},leave:(N,A)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,A,v)}})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Hf=oi([Me(0,fn),Me(1,pn),Me(2,My)],Hf);function MC(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Lu=Ui("CharSizeService"),Qr=Ui("CoreBrowserService"),Ip=Ui("MouseService"),Jr=Ui("RenderService"),DC=Ui("SelectionService"),Dy=Ui("CharacterJoinerService"),ol=Ui("ThemeService"),By=Ui("LinkProviderService"),BC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ub.isErrorNoTelemetry(e)?new ub(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},LC=new BC;function hu(e){OC(e)||LC.onUnexpectedError(e)}var Uf="Canceled";function OC(e){return e instanceof zC?!0:e instanceof Error&&e.name===Uf&&e.message===Uf}var zC=class extends Error{constructor(){super(Uf),this.name=this.message}};function PC(e){return new Error(`Illegal argument: ${e}`)}var ub=class $f extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $f)return t;let i=new $f;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ff=class Ly extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Ly.prototype)}};function In(e,t=0){return e[e.length-(1+t)]}var IC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(IC||(IC={}));function HC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Oy;(e=>{function t(J){return J&&typeof J=="object"&&typeof J[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(J){yield J}e.single=a;function o(J){return t(J)?J:a(J)}e.wrap=o;function c(J){return J||i}e.from=c;function*h(J){for(let q=J.length-1;q>=0;q--)yield J[q]}e.reverse=h;function p(J){return!J||J[Symbol.iterator]().next().done===!0}e.isEmpty=p;function d(J){return J[Symbol.iterator]().next().value}e.first=d;function _(J,q){let L=0;for(let Z of J)if(q(Z,L++))return!0;return!1}e.some=_;function x(J,q){for(let L of J)if(q(L))return L}e.find=x;function*b(J,q){for(let L of J)q(L)&&(yield L)}e.filter=b;function*v(J,q){let L=0;for(let Z of J)yield q(Z,L++)}e.map=v;function*y(J,q){let L=0;for(let Z of J)yield*q(Z,L++)}e.flatMap=y;function*N(...J){for(let q of J)yield*q}e.concat=N;function A(J,q,L){let Z=L;for(let he of J)Z=q(Z,he);return Z}e.reduce=A;function*E(J,q,L=J.length){for(q<0&&(q+=J.length),L<0?L+=J.length:L>J.length&&(L=J.length);q1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function UC(...e){return Jt(()=>aa(e))}function Jt(e){return{dispose:HC(()=>{e()})}}var zy=class Py{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{aa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Py.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};zy.DISABLE_DISPOSED_WARNING=!1;var Ms=zy,ft=class{constructor(){this._store=new Ms,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ft.None=Object.freeze({dispose(){}});var sl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Zr=typeof window=="object"?window:globalThis,qf=class Wf{constructor(t){this.element=t,this.next=Wf.Undefined,this.prev=Wf.Undefined}};qf.Undefined=new qf(void 0);var ii=qf,hb=class{constructor(){this._first=ii.Undefined,this._last=ii.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ii.Undefined}clear(){let e=this._first;for(;e!==ii.Undefined;){let t=e.next;e.prev=ii.Undefined,e.next=ii.Undefined,e=t}this._first=ii.Undefined,this._last=ii.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ii(e);if(this._first===ii.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==ii.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ii.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ii.Undefined&&e.next!==ii.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ii.Undefined&&e.next===ii.Undefined?(this._first=ii.Undefined,this._last=ii.Undefined):e.next===ii.Undefined?(this._last=this._last.prev,this._last.next=ii.Undefined):e.prev===ii.Undefined&&(this._first=this._first.next,this._first.prev=ii.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ii.Undefined;)yield e.element,e=e.next}},$C=globalThis.performance&&typeof globalThis.performance.now=="function",FC=class Iy{static create(t){return new Iy(t)}constructor(t){this._now=$C&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Vi;(e=>{e.None=()=>ft.None;function t(W,G){return x(W,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(W){return(G,X=null,I)=>{let j=!1,O;return O=W(B=>{if(!j)return O?O.dispose():j=!0,G.call(X,B)},null,I),j&&O.dispose(),O}}e.once=i;function s(W,G,X){return d((I,j=null,O)=>W(B=>I.call(j,G(B)),null,O),X)}e.map=s;function a(W,G,X){return d((I,j=null,O)=>W(B=>{G(B),I.call(j,B)},null,O),X)}e.forEach=a;function o(W,G,X){return d((I,j=null,O)=>W(B=>G(B)&&I.call(j,B),null,O),X)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(G,X=null,I)=>{let j=UC(...W.map(O=>O(B=>G.call(X,B))));return _(j,I)}}e.any=h;function p(W,G,X,I){let j=X;return s(W,O=>(j=G(j,O),j),I)}e.reduce=p;function d(W,G){let X,I={onWillAddFirstListener(){X=W(j.fire,j)},onDidRemoveLastListener(){X==null||X.dispose()}},j=new ke(I);return G==null||G.add(j),j.event}function _(W,G){return G instanceof Array?G.push(W):G&&G.add(W),W}function x(W,G,X=100,I=!1,j=!1,O,B){let xe,T,R,Y=0,C,se={leakWarningThreshold:O,onWillAddFirstListener(){xe=W(oe=>{Y++,T=G(T,oe),I&&!R&&(te.fire(T),T=void 0),C=()=>{let $=T;T=void 0,R=void 0,(!I||Y>1)&&te.fire($),Y=0},typeof X=="number"?(clearTimeout(R),R=setTimeout(C,X)):R===void 0&&(R=0,queueMicrotask(C))})},onWillRemoveListener(){j&&Y>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},te=new ke(se);return B==null||B.add(te),te.event}e.debounce=x;function b(W,G=0,X){return e.debounce(W,(I,j)=>I?(I.push(j),I):[j],G,void 0,!0,void 0,X)}e.accumulate=b;function v(W,G=(I,j)=>I===j,X){let I=!0,j;return o(W,O=>{let B=I||!G(O,j);return I=!1,j=O,B},X)}e.latch=v;function y(W,G,X){return[e.filter(W,G,X),e.filter(W,I=>!G(I),X)]}e.split=y;function N(W,G=!1,X=[],I){let j=X.slice(),O=W(T=>{j?j.push(T):xe.fire(T)});I&&I.add(O);let B=()=>{j==null||j.forEach(T=>xe.fire(T)),j=null},xe=new ke({onWillAddFirstListener(){O||(O=W(T=>xe.fire(T)),I&&I.add(O))},onDidAddFirstListener(){j&&(G?setTimeout(B):B())},onDidRemoveLastListener(){O&&O.dispose(),O=null}});return I&&I.add(xe),xe.event}e.buffer=N;function A(W,G){return(X,I,j)=>{let O=G(new D);return W(function(B){let xe=O.evaluate(B);xe!==E&&X.call(I,xe)},void 0,j)}}e.chain=A;let E=Symbol("HaltChainable");class D{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(X=>(G(X),X)),this}filter(G){return this.steps.push(X=>G(X)?X:E),this}reduce(G,X){let I=X;return this.steps.push(j=>(I=G(I,j),I)),this}latch(G=(X,I)=>X===I){let X=!0,I;return this.steps.push(j=>{let O=X||!G(j,I);return X=!1,I=j,O?j:E}),this}evaluate(G){for(let X of this.steps)if(G=X(G),G===E)break;return G}}function P(W,G,X=I=>I){let I=(...xe)=>B.fire(X(...xe)),j=()=>W.on(G,I),O=()=>W.removeListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:O});return B.event}e.fromNodeEventEmitter=P;function J(W,G,X=I=>I){let I=(...xe)=>B.fire(X(...xe)),j=()=>W.addEventListener(G,I),O=()=>W.removeEventListener(G,I),B=new ke({onWillAddFirstListener:j,onDidRemoveLastListener:O});return B.event}e.fromDOMEventEmitter=J;function q(W){return new Promise(G=>i(W)(G))}e.toPromise=q;function L(W){let G=new ke;return W.then(X=>{G.fire(X)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=L;function Z(W,G){return W(X=>G.fire(X))}e.forward=Z;function he(W,G,X){return G(X),W(I=>G(I))}e.runAndSubscribe=he;class ye{constructor(G,X){this._observable=G,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(I),X&&X.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,X){this._hasChanged=!0}endUpdate(G){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function U(W,G){return new ye(W,G).emitter.event}e.fromObservable=U;function re(W){return(G,X,I)=>{let j=0,O=!1,B={beginUpdate(){j++},endUpdate(){j--,j===0&&(W.reportChanges(),O&&(O=!1,G.call(X)))},handlePossibleChange(){},handleChange(){O=!0}};W.addObserver(B),W.reportChanges();let xe={dispose(){W.removeObserver(B)}};return I instanceof Ms?I.add(xe):Array.isArray(I)&&I.push(xe),xe}}e.fromObservableLight=re})(Vi||(Vi={}));var Gf=class Yf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Yf._idPool++}`,Yf.all.add(this)}start(t){this._stopWatch=new FC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Gf.all=new Set,Gf._idPool=0;var qC=Gf,WC=-1,Hy=class Uy{constructor(t,i,s=(Uy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{var h,p,d,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],y=new VC(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||hu)(y),ft.None}if(this._disposed)return ft.None;i&&(t=t.bind(i));let a=new Qd(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=YC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof Qd?(this._deliveryQueue??(this._deliveryQueue=new JC),this._listeners=[this._listeners,a]):this._listeners.push(a):((d=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||d.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=Jt(()=>{o==null||o(),this._removeListener(a)});return s instanceof Ms?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*ZC<=i.length){let d=0;for(let _=0;_0}},JC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Kf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ke,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ke,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Kf.INSTANCE=new Kf;var Hp=Kf;function ek(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Hp.INSTANCE.onDidChangeZoomLevel;function tk(e){return Hp.INSTANCE.getZoomFactor(e)}Hp.INSTANCE.onDidChangeFullscreen;var cl=typeof navigator=="object"?navigator.userAgent:"",Vf=cl.indexOf("Firefox")>=0,ik=cl.indexOf("AppleWebKit")>=0,Up=cl.indexOf("Chrome")>=0,nk=!Up&&cl.indexOf("Safari")>=0;cl.indexOf("Electron/")>=0;cl.indexOf("Android")>=0;var Jd=!1;if(typeof Zr.matchMedia=="function"){let e=Zr.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Zr.matchMedia("(display-mode: fullscreen)");Jd=e.matches,ek(Zr,e,({matches:i})=>{Jd&&t.matches||(Jd=i)})}var tl="en",Xf=!1,Zf=!1,du=!1,Fy=!1,Kc,fu=tl,db=tl,rk,fr,sa=globalThis,Ki,by;typeof sa.vscode<"u"&&typeof sa.vscode.process<"u"?Ki=sa.vscode.process:typeof process<"u"&&typeof((by=process==null?void 0:process.versions)==null?void 0:by.node)=="string"&&(Ki=process);var vy,sk=typeof((vy=Ki==null?void 0:Ki.versions)==null?void 0:vy.electron)=="string",ak=sk&&(Ki==null?void 0:Ki.type)==="renderer",yy;if(typeof Ki=="object"){Xf=Ki.platform==="win32",Zf=Ki.platform==="darwin",du=Ki.platform==="linux",du&&Ki.env.SNAP&&Ki.env.SNAP_REVISION,Ki.env.CI||Ki.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Kc=tl,fu=tl;let e=Ki.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Kc=t.userLocale,db=t.osLocale,fu=t.resolvedLanguage||tl,rk=(yy=t.languagePack)==null?void 0:yy.translationsConfigFile}catch{}Fy=!0}else typeof navigator=="object"&&!ak?(fr=navigator.userAgent,Xf=fr.indexOf("Windows")>=0,Zf=fr.indexOf("Macintosh")>=0,(fr.indexOf("Macintosh")>=0||fr.indexOf("iPad")>=0||fr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,du=fr.indexOf("Linux")>=0,(fr==null?void 0:fr.indexOf("Mobi"))>=0,fu=globalThis._VSCODE_NLS_LANGUAGE||tl,Kc=navigator.language.toLowerCase(),db=Kc):console.error("Unable to resolve platform.");var qy=Xf,Nr=Zf,lk=du,fb=Fy,Tr=fr,ks=fu,ok;(e=>{function t(){return ks}e.value=t;function i(){return ks.length===2?ks==="en":ks.length>=3?ks[0]==="e"&&ks[1]==="n"&&ks[2]==="-":!1}e.isDefaultVariant=i;function s(){return ks==="en"}e.isDefault=s})(ok||(ok={}));var ck=typeof sa.postMessage=="function"&&!sa.importScripts;(()=>{if(ck){let e=[];sa.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),sa.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var uk=!!(Tr&&Tr.indexOf("Chrome")>=0);Tr&&Tr.indexOf("Firefox")>=0;!uk&&Tr&&Tr.indexOf("Safari")>=0;Tr&&Tr.indexOf("Edg/")>=0;Tr&&Tr.indexOf("Android")>=0;var Ka=typeof navigator=="object"?navigator:{};fb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ka&&Ka.clipboard&&Ka.clipboard.writeText,fb||Ka&&Ka.clipboard&&Ka.clipboard.readText;var $p=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ef=new $p,pb=new $p,mb=new $p,hk=new Array(230),Wy;(e=>{function t(h){return ef.keyCodeToStr(h)}e.toString=t;function i(h){return ef.strToKeyCode(h)}e.fromString=i;function s(h){return pb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return mb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return pb.strToKeyCode(h)||mb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return ef.keyCodeToStr(h)}e.toElectronAccelerator=c})(Wy||(Wy={}));var dk=class Gy{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof Gy&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new fk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},fk=class{constructor(e){if(e.length===0)throw PC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof Sk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Vi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Yy})})(yk||(yk={}));var Sk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Yy:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Fp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ff("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},wk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Jt(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ck;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(Ck||(Ck={}));var bb=class ir{static fromArray(t){return new ir(i=>{i.emitMany(t)})}static fromPromise(t){return new ir(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ir(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ir(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ke,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ir(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ir.map(this,t)}static filter(t,i){return new ir(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ir.filter(this,t)}static coalesce(t){return ir.filter(t,i=>!!i)}coalesce(){return ir.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ir.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};bb.EMPTY=bb.fromArray([]);var{getWindow:Cr,getWindowId:kk,onDidRegisterWindow:Ek}=(function(){let e=new Map,t={window:Zr,disposables:new Ms};e.set(Zr.vscodeWindowId,t);let i=new ke,s=new ke,a=new ke;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ft.None;let h=new Ms,p={window:c,disposables:h.add(new Ms)};return e.set(c.vscodeWindowId,p),h.add(Jt(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ye(c,Di.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var d;let h=c;if((d=h==null?void 0:h.ownerDocument)!=null&&d.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:Zr},getDocument(c){return Cr(c).document}}})(),Nk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ye(e,t,i,s){return new Nk(e,t,i,s)}var vb=function(e,t,i,s){return Ye(e,t,i,s)},qp,Tk=class extends wk{constructor(e){super(),this.defaultTarget=e&&Cr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},yb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){hu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(yb.sort),c.shift().execute();s.set(o,!1)};qp=(o,c,h=0)=>{let p=kk(o),d=new yb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(d),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),d}})();function jk(e){let t=e.getBoundingClientRect(),i=Cr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Di={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Ak=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Cn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Cn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Cn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Cn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Cn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Cn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Cn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Cn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Cn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Cn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Cn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Cn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Cn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Cn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Cn(e){return typeof e=="number"?`${e}px`:e}function bo(e){return new Ak(e)}var Ky=class{constructor(){this._hooks=new Ms,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(Jt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Cr(e)}this._hooks.add(Ye(o,Di.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ye(o,Di.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Rk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Sr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Sr||(Sr={}));var po=class en extends ft{constructor(){super(),this.dispatched=!1,this.targets=new hb,this.ignoreTargets=new hb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Vi.runAndSubscribe(Ek,({window:t,disposables:i})=>{i.add(Ye(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ye(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ye(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:Zr,disposables:this._store}))}static addTarget(t){if(!en.isTouchDevice())return ft.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.targets.push(t);return Jt(i)}static ignoreTarget(t){if(!en.isTouchDevice())return ft.None;en.INSTANCE||(en.INSTANCE=new en);let i=en.INSTANCE.ignoreTargets.push(t);return Jt(i)}static isTouchDevice(){return"ontouchstart"in Zr||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=en.HOLD_DELAY&&Math.abs(p.initialPageX-In(p.rollingPageX))<30&&Math.abs(p.initialPageY-In(p.rollingPageY))<30){let _=this.newGestureEvent(Sr.Contextmenu,p.initialTarget);_.pageX=In(p.rollingPageX),_.pageY=In(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=In(p.rollingPageX),x=In(p.rollingPageY),b=In(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],y=x-p.rollingPageY[0],N=[...this.targets].filter(A=>p.initialTarget instanceof Node&&A.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(y)/b,y>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Sr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Sr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>en.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Sr.Change||t.type===Sr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,d){this.handle=qp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,y=!0;a+=en.SCROLL_FRICTION*x,h+=en.SCROLL_FRICTION*x,a>0&&(y=!1,b=o*a*x),h>0&&(y=!1,v=p*h*x);let N=this.newGestureEvent(Sr.Change);N.translationX=b,N.translationY=v,i.forEach(A=>A.dispatchEvent(N)),y||this.inertia(t,i,_,a,o,c+b,h,p,d+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};po.SCROLL_FRICTION=-.005,po.HOLD_DELAY=700,po.CLEAR_TAP_COUNT_TIME=400,oi([Rk],po,"isTouchDevice",1);var Mk=po,Wp=class extends ft{onclick(e,t){this._register(Ye(e,Di.CLICK,i=>t(new Vc(Cr(e),i))))}onmousedown(e,t){this._register(Ye(e,Di.MOUSE_DOWN,i=>t(new Vc(Cr(e),i))))}onmouseover(e,t){this._register(Ye(e,Di.MOUSE_OVER,i=>t(new Vc(Cr(e),i))))}onmouseleave(e,t){this._register(Ye(e,Di.MOUSE_LEAVE,i=>t(new Vc(Cr(e),i))))}onkeydown(e,t){this._register(Ye(e,Di.KEY_DOWN,i=>t(new gb(i))))}onkeyup(e,t){this._register(Ye(e,Di.KEY_UP,i=>t(new gb(i))))}oninput(e,t){this._register(Ye(e,Di.INPUT,t))}onblur(e,t){this._register(Ye(e,Di.BLUR,t))}onfocus(e,t){this._register(Ye(e,Di.FOCUS,t))}onchange(e,t){this._register(Ye(e,Di.CHANGE,t))}ignoreGesture(e){return Mk.ignoreTarget(e)}},Sb=11,Dk=class extends Wp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Sb+"px",this.domNode.style.height=Sb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ky),this._register(vb(this.bgDomNode,Di.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(vb(this.domNode,Di.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Tk),this._pointerdownScheduleRepeatTimer=this._register(new Fp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Cr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Bk=class Qf{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Qf(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qf(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Lk=class extends ft{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Bk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Cb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Cb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},wb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function tf(e,t){let i=t-e;return function(s){return e+i*Pk(s)}}function Ok(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Hk=140,Vy=class extends Wp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Ik(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ky),this._shouldRender=!0,this.domNode=bo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ye(this.domNode.domNode,Di.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Dk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=bo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ye(this.slider.domNode,Di.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=jk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(qy&&c>Hk){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Xy=class ep{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ep(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let d=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-d)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(d),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=ep._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),d=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%d===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};tp.INSTANCE=new tp;var Wk=tp,Gk=class extends Wp{constructor(e,t,i){super(),this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ke),this.onWillScroll=this._onWillScroll.event,this._options=Kk(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new $k(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Uk(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=bo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=bo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=bo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Fp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=aa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Nr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new _b(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=aa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new _b(i))};this._mouseWheelToDispose.push(Ye(this._listenOnDomNode,Di.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Wk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Nr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),d={};if(o){let _=kb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(d,x)}if(c){let _=kb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(d,x)}d=this._scrollable.validateScrollPosition(d),(p.scrollLeft!==d.scrollLeft||p.scrollTop!==d.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(d):this._scrollable.setScrollPositionNow(d),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Fk)}},Yk=class extends Gk{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Kk(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Nr&&(t.className+=" mac"),t}var ip=class extends ft{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Lk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:d=>qp(s.window,d)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Yk(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(d=>{this._scrollableElement.updateOptions({handleMouseWheel:!(d&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Vi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Jt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Jt(()=>this._styleElement.remove())),this._register(Vi.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(d=>this._handleScroll(d)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ip=oi([Me(2,fn),Me(3,Qr),Me(4,Ay),Me(5,ol),Me(6,pn),Me(7,Jr)],ip);var np=class extends ft{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(Jt(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};np=oi([Me(1,fn),Me(2,Qr),Me(3,Ro),Me(4,Jr)],np);var Vk=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},vr={full:0,left:0,center:0,right:0},Es={full:0,left:0,center:0,right:0},no={full:0,left:0,center:0,right:0},Cu=class extends ft{constructor(e,t,i,s,a,o,c,h){var d;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new Vk,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(d=this._viewportElement.parentElement)==null||d.insertBefore(this._canvas,this._viewportElement),this._register(Jt(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Es.full=this._canvas.width,Es.left=e,Es.center=t,Es.right=e,this._refreshDrawHeightConstants(),no.full=1,no.left=1,no.center=1+Es.left,no.right=1+Es.left+Es.center}_refreshDrawHeightConstants(){vr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);vr.left=t,vr.center=t,vr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(no[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-vr[e.position||"full"]/2),Es[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+vr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Cu=oi([Me(2,fn),Me(3,Ro),Me(4,Jr),Me(5,pn),Me(6,ol),Me(7,Qr)],Cu);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var pu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(pu||(pu={}));var Zy;(e=>e.ST=`${pe.ESC}\\`)(Zy||(Zy={}));var rp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};rp=oi([Me(2,fn),Me(3,pn),Me(4,ca),Me(5,Jr)],rp);var Bi=0,Li=0,Oi=0,ai=0,Eb={css:"#00000000",rgba:0},Ci;(e=>{function t(a,o,c,h){return h!==void 0?`#${Qs(a)}${Qs(o)}${Qs(c)}${Qs(h)}`:`#${Qs(a)}${Qs(o)}${Qs(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(Ci||(Ci={}));var Xt;(e=>{function t(p,d){if(ai=(d.rgba&255)/255,ai===1)return{css:d.css,rgba:d.rgba};let _=d.rgba>>24&255,x=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,N=p.rgba>>8&255;Bi=v+Math.round((_-v)*ai),Li=y+Math.round((x-y)*ai),Oi=N+Math.round((b-N)*ai);let A=Ci.toCss(Bi,Li,Oi),E=Ci.toRgba(Bi,Li,Oi);return{css:A,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,_){let x=mu.ensureContrastRatio(p.rgba,d.rgba,_);if(x)return Ci.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[Bi,Li,Oi]=mu.toChannels(d),{css:Ci.toCss(Bi,Li,Oi),rgba:d}}e.opaque=a;function o(p,d){return ai=Math.round(d*255),[Bi,Li,Oi]=mu.toChannels(p.rgba),{css:Ci.toCss(Bi,Li,Oi,ai),rgba:Ci.toRgba(Bi,Li,Oi,ai)}}e.opacity=o;function c(p,d){return ai=p.rgba&255,o(p,ai*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Xt||(Xt={}));var ni;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Bi=parseInt(a.slice(1,2).repeat(2),16),Li=parseInt(a.slice(2,3).repeat(2),16),Oi=parseInt(a.slice(3,4).repeat(2),16),Ci.toColor(Bi,Li,Oi);case 5:return Bi=parseInt(a.slice(1,2).repeat(2),16),Li=parseInt(a.slice(2,3).repeat(2),16),Oi=parseInt(a.slice(3,4).repeat(2),16),ai=parseInt(a.slice(4,5).repeat(2),16),Ci.toColor(Bi,Li,Oi,ai);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Bi=parseInt(o[1]),Li=parseInt(o[2]),Oi=parseInt(o[3]),ai=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ci.toColor(Bi,Li,Oi,ai);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Bi,Li,Oi,ai]=t.getImageData(0,0,1,1).data,ai!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ci.toRgba(Bi,Li,Oi,ai),css:a}}e.toColor=s})(ni||(ni={}));var un;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(un||(un={}));var mu;(e=>{function t(c,h){if(ai=(h&255)/255,ai===1)return h;let p=h>>24&255,d=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Bi=x+Math.round((p-x)*ai),Li=b+Math.round((d-b)*ai),Oi=v+Math.round((_-v)*ai),Ci.toRgba(Bi,Li,Oi)}e.blend=t;function i(c,h,p){let d=un.relativeLuminance(c>>8),_=un.relativeLuminance(h>>8);if(Yr(d,_)>8));if(y>8));return y>A?v:N}return v}let x=a(c,h,p),b=Yr(d,un.relativeLuminance(x>>8));if(b>8));return b>y?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Yr(un.relativeLuminance2(b,v,y),un.relativeLuminance2(d,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(mu||(mu={}));function Qs(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Yr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=d,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Rs.length}if(this._bufferService.cols-a>1){let d=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=U,O=G,B=this._workCell;if(b.length>0&&G===b[0][0]&&j){let je=b.shift(),Ze=this._isCellInSelection(je[0],t);for(D=je[0]+1;D=je[1]),j?(I=!0,B=new Xk(this._workCell,e.translateToString(!0,je[0],je[1]),je[1]-je[0]),O=je[1]-1,X=B.getWidth()):U=je[1]}let xe=this._isCellInSelection(G,t),T=i&&G===o,R=W&&G>=d&&G<=_,Y=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{Y=!0});let C=B.getChars()||Rs;if(C===" "&&(B.isUnderline()||B.isOverline())&&(C=" "),ye=X*h-p.get(C,B.isBold(),B.isItalic()),!N)N=this._document.createElement("span");else if(A&&(xe&&he||!xe&&!he&&B.bg===P)&&(xe&&he&&v.selectionForeground||B.fg===J)&&B.extended.ext===q&&R===L&&ye===Z&&!T&&!I&&!Y&&j){B.isInvisible()?E+=Rs:E+=C,A++;continue}else A&&(N.textContent=E),N=this._document.createElement("span"),A=0,E="";if(P=B.bg,J=B.fg,q=B.extended.ext,L=R,Z=ye,he=xe,I&&o>=G&&o<=O&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(re.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&re.push("xterm-cursor-blink"),re.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":re.push("xterm-cursor-outline");break;case"block":re.push("xterm-cursor-block");break;case"bar":re.push("xterm-cursor-bar");break;case"underline":re.push("xterm-cursor-underline");break}}if(B.isBold()&&re.push("xterm-bold"),B.isItalic()&&re.push("xterm-italic"),B.isDim()&&re.push("xterm-dim"),B.isInvisible()?E=Rs:E=B.getChars()||Rs,B.isUnderline()&&(re.push(`xterm-underline-${B.extended.underlineStyle}`),E===" "&&(E=" "),!B.isUnderlineColorDefault()))if(B.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Ao.toColorRGB(B.getUnderlineColor()).join(",")})`;else{let je=B.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&B.isBold()&&je<8&&(je+=8),N.style.textDecorationColor=v.ansi[je].css}B.isOverline()&&(re.push("xterm-overline"),E===" "&&(E=" ")),B.isStrikethrough()&&re.push("xterm-strikethrough"),R&&(N.style.textDecoration="underline");let se=B.getFgColor(),te=B.getFgColorMode(),oe=B.getBgColor(),$=B.getBgColorMode(),ue=!!B.isInverse();if(ue){let je=se;se=oe,oe=je;let Ze=te;te=$,$=Ze}let be,De,Ee=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,je=>{je.options.layer!=="top"&&Ee||(je.backgroundColorRGB&&($=50331648,oe=je.backgroundColorRGB.rgba>>8&16777215,be=je.backgroundColorRGB),je.foregroundColorRGB&&(te=50331648,se=je.foregroundColorRGB.rgba>>8&16777215,De=je.foregroundColorRGB),Ee=je.options.layer==="top")}),!Ee&&xe&&(be=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=be.rgba>>8&16777215,$=50331648,Ee=!0,v.selectionForeground&&(te=50331648,se=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),Ee&&re.push("xterm-decoration-top");let Be;switch($){case 16777216:case 33554432:Be=v.ansi[oe],re.push(`xterm-bg-${oe}`);break;case 50331648:Be=Ci.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Nb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:ue?(Be=v.foreground,re.push("xterm-bg-257")):Be=v.background}switch(be||B.isDim()&&(be=Xt.multiplyOpacity(Be,.5)),te){case 16777216:case 33554432:B.isBold()&&se<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(se+=8),this._applyMinimumContrast(N,Be,v.ansi[se],B,be,void 0)||re.push(`xterm-fg-${se}`);break;case 50331648:let je=Ci.toColor(se>>16&255,se>>8&255,se&255);this._applyMinimumContrast(N,Be,je,B,be,De)||this._addStyle(N,`color:#${Nb(se.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Be,v.foreground,B,be,De)||ue&&re.push("xterm-fg-257")}re.length&&(N.className=re.join(" "),re.length=0),!T&&!I&&!Y&&j?A++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=O}return N&&A&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||Jk(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Xt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};sp=oi([Me(1,Dy),Me(2,pn),Me(3,Qr),Me(4,ca),Me(5,Ro),Me(6,ol)],sp);function Nb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},i2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function n2(){return new i2}var nf="xterm-dom-renderer-owner-",tr="xterm-rows",Zc="xterm-fg-",Tb="xterm-bg-",ro="xterm-focus",Qc="xterm-selection",r2=1,ap=class extends ft{constructor(e,t,i,s,a,o,c,h,p,d,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=d,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=r2++,this._rowElements=[],this._selectionRenderModel=n2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(tr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Qc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=e2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(y=>this._injectCss(y))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(sp,document),this._element.classList.add(nf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(y=>this._handleLinkHover(y))),this._register(this._linkifier2.onHideLinkUnderline(y=>this._handleLinkLeave(y))),this._register(Jt(()=>{this._element.classList.remove(nf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new t2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tr} .xterm-dim { color: ${Xt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Qc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Qc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Qc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${Zc}${o} { color: ${c.css}; }${this._terminalSelector} .${Zc}${o}.xterm-dim { color: ${Xt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Tb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${Zc}257 { color: ${Xt.opaque(e.background).css}; }${this._terminalSelector} .${Zc}257.xterm-dim { color: ${Xt.multiplyOpacity(Xt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Tb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ro),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ro),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,d=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,d));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let d=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(d);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,d,d===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${nf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,d=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let y=v+h.ydisp,N=this._rowElements[v],A=h.lines.get(y);if(!N||!A)break;N.replaceChildren(...this._rowFactory.createRow(A,y,y===p,x,b,d,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};ap=oi([Me(7,Pp),Me(8,Lu),Me(9,pn),Me(10,fn),Me(11,ca),Me(12,Qr),Me(13,ol)],ap);var lp=class extends ft{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ke),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new a2(this._optionsService))}catch{this._measureStrategy=this._register(new s2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lp=oi([Me(2,pn)],lp);var Qy=class extends ft{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},s2=class extends Qy{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},a2=class extends Qy{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},l2=class extends ft{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new o2(this._window)),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ke),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Vi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ye(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ye(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},o2=class extends ft{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new sl),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Jt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ye(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},c2=class extends ft{constructor(){super(),this.linkProviders=[],this._register(Jt(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Gp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function u2(e,t,i,s,a,o,c,h,p){if(!o)return;let d=Gp(e,t,i);if(d)return d[0]=Math.ceil((d[0]+(p?c/2:0))/c),d[1]=Math.ceil(d[1]/h),d[0]=Math.min(Math.max(d[0],1),s+(p?1:0)),d[1]=Math.min(Math.max(d[1],1),a),d}var op=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return u2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Gp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};op=oi([Me(0,Jr),Me(1,Lu)],op);var h2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Jy={};yC(Jy,{getSafariVersion:()=>f2,isChromeOS:()=>n0,isFirefox:()=>e0,isIpad:()=>p2,isIphone:()=>m2,isLegacyEdge:()=>d2,isLinux:()=>Yp,isMac:()=>Eu,isNode:()=>Ou,isSafari:()=>t0,isWindows:()=>i0});var Ou=typeof process<"u"&&"title"in process,Mo=Ou?"node":navigator.userAgent,Do=Ou?"node":navigator.platform,e0=Mo.includes("Firefox"),d2=Mo.includes("Edge"),t0=/^((?!chrome|android).)*safari/i.test(Mo);function f2(){if(!t0)return 0;let e=Mo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Eu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Do),p2=Do==="iPad",m2=Do==="iPhone",i0=["Windows","Win16","Win32","WinCE"].includes(Do),Yp=Do.indexOf("Linux")>=0,n0=/\bCrOS\b/.test(Mo),r0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},g2=class extends r0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},x2=class extends r0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Nu=!Ou&&"requestIdleCallback"in window?x2:g2,_2=class{constructor(){this._queue=new Nu}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cp=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new sl),this._pausedResizeTask=new _2,this._observerDisposable=this._register(new sl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ke),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ke),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ke),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new h2((d,_)=>this._renderRows(d,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new b2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Jt(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var d;return(d=this._renderer.value)==null?void 0:d.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(d=>this._registerIntersectionObserver(d,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Jt(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cp=oi([Me(2,pn),Me(3,Lu),Me(4,ca),Me(5,Ro),Me(6,fn),Me(7,Qr),Me(8,ol)],cp);var b2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function v2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return w2(a,o,e,t,i,s)+zu(o,t,i,s)+C2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Co(Math.abs(a-e),wo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=S2(o>t?e:a,i)+(h-1)*i.cols+1+y2(o>t?a:e);return Co(p,wo(c,s))}function y2(e,t){return e-1}function S2(e,t){return t.cols-e}function w2(e,t,i,s,a,o){return zu(t,s,a,o).length===0?"":Co(a0(e,t,e,t-la(t,a),!1,a).length,wo("D",o))}function zu(e,t,i,s){let a=e-la(e,i),o=t-la(t,i),c=Math.abs(a-o)-k2(e,t,i);return Co(c,wo(s0(e,t),s))}function C2(e,t,i,s,a,o){let c;zu(t,s,a,o).length>0?c=s-la(s,a):c=t;let h=s,p=E2(e,t,i,s,a,o);return Co(a0(e,c,i,h,p==="C",a).length,wo(p,o))}function k2(e,t,i){var c;let s=0,a=e-la(e,i),o=t-la(t,i);for(let h=0;h=0&&e0?c=s-la(s,a):c=t,e=i&&ct?"A":"B"}function a0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function wo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Co(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function jb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var rf=50,T2=15,j2=50,A2=500,R2=" ",M2=new RegExp(R2,"g"),up=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ke),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ke),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=d=>this._handleMouseMove(d),this._mouseUpListener=d=>this._handleMouseUp(d),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(d=>this._handleTrim(d)),this._register(this._bufferService.buffers.onBufferActivate(d=>this._handleBufferActivate(d))),this.enable(),this._model=new N2(this._bufferService),this._activeSelectionMode=0,this._register(Jt(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(d=>{d.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(M2," ")).join(i0?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Yp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=jb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Gp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-rf),rf),t/=rf,t/Math.abs(t)+Math.round(t*(T2-1)))}shouldForceSelection(e){return Eu?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),j2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Eu&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,d=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=D-1,p+=D-1);A>0&&h>0&&!this._isCharWordSeparator(o.loadCell(A-1,this._workCell));){o.loadCell(A-1,this._workCell);let P=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,A--):P>1&&(b+=P-1,h-=P-1),h--,A--}for(;E1&&(v+=P-1,p+=P-1),p++,E++}}p++;let y=h+d-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&y===0&&o.getCodePoint(0)!==32){let A=a.lines.get(e[1]-1);if(A&&o.isWrapped&&A.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let D=this._bufferService.cols-E.start;y-=D,N+=D}}}if(s&&y+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let A=a.lines.get(e[1]+1);if(A!=null&&A.isWrapped&&A.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:y,length:N}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=jb(i,this._bufferService.cols)}};up=oi([Me(3,fn),Me(4,ca),Me(5,Ip),Me(6,pn),Me(7,Jr),Me(8,Qr)],up);var Ab=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Rb=class{constructor(){this._color=new Ab,this._css=new Ab}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[ni.toColor("#2e3436"),ni.toColor("#cc0000"),ni.toColor("#4e9a06"),ni.toColor("#c4a000"),ni.toColor("#3465a4"),ni.toColor("#75507b"),ni.toColor("#06989a"),ni.toColor("#d3d7cf"),ni.toColor("#555753"),ni.toColor("#ef2929"),ni.toColor("#8ae234"),ni.toColor("#fce94f"),ni.toColor("#729fcf"),ni.toColor("#ad7fa8"),ni.toColor("#34e2e2"),ni.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Ci.toCss(s,a,o),rgba:Ci.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ci.toCss(s,s,s),rgba:Ci.toRgba(s,s,s)})}return e})()),ia=ni.toColor("#ffffff"),mo=ni.toColor("#000000"),Mb=ni.toColor("#ffffff"),Db=mo,so={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},D2=ia,hp=class extends ft{constructor(e){super(),this._optionsService=e,this._contrastCache=new Rb,this._halfContrastCache=new Rb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ia,background:mo,cursor:Mb,cursorAccent:Db,selectionForeground:void 0,selectionBackgroundTransparent:so,selectionBackgroundOpaque:Xt.blend(mo,so),selectionInactiveBackgroundTransparent:so,selectionInactiveBackgroundOpaque:Xt.blend(mo,so),scrollbarSliderBackground:Xt.opacity(ia,.2),scrollbarSliderHoverBackground:Xt.opacity(ia,.4),scrollbarSliderActiveBackground:Xt.opacity(ia,.5),overviewRulerBorder:ia,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Ut(e.foreground,ia),t.background=Ut(e.background,mo),t.cursor=Xt.blend(t.background,Ut(e.cursor,Mb)),t.cursorAccent=Xt.blend(t.background,Ut(e.cursorAccent,Db)),t.selectionBackgroundTransparent=Ut(e.selectionBackground,so),t.selectionBackgroundOpaque=Xt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Ut(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Xt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Ut(e.selectionForeground,Eb):void 0,t.selectionForeground===Eb&&(t.selectionForeground=void 0),Xt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Xt.opacity(t.selectionBackgroundTransparent,.3)),Xt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Xt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Ut(e.scrollbarSliderBackground,Xt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Ut(e.scrollbarSliderHoverBackground,Xt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Ut(e.scrollbarSliderActiveBackground,Xt.opacity(t.foreground,.5)),t.overviewRulerBorder=Ut(e.overviewRulerBorder,D2),t.ansi=Ti.slice(),t.ansi[0]=Ut(e.black,Ti[0]),t.ansi[1]=Ut(e.red,Ti[1]),t.ansi[2]=Ut(e.green,Ti[2]),t.ansi[3]=Ut(e.yellow,Ti[3]),t.ansi[4]=Ut(e.blue,Ti[4]),t.ansi[5]=Ut(e.magenta,Ti[5]),t.ansi[6]=Ut(e.cyan,Ti[6]),t.ansi[7]=Ut(e.white,Ti[7]),t.ansi[8]=Ut(e.brightBlack,Ti[8]),t.ansi[9]=Ut(e.brightRed,Ti[9]),t.ansi[10]=Ut(e.brightGreen,Ti[10]),t.ansi[11]=Ut(e.brightYellow,Ti[11]),t.ansi[12]=Ut(e.brightBlue,Ti[12]),t.ansi[13]=Ut(e.brightMagenta,Ti[13]),t.ansi[14]=Ut(e.brightCyan,Ti[14]),t.ansi[15]=Ut(e.brightWhite,Ti[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},O2={trace:0,debug:1,info:2,warn:3,error:4,off:5},z2="xterm.js: ",dp=class extends ft{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=O2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*dt+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*dt+0]=t|2097152|i[2]<<22):this._data[t*dt+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*dt+0]>>22}hasWidth(t){return this._data[t*dt+0]&12582912}getFg(t){return this._data[t*dt+1]}getBg(t){return this._data[t*dt+2]}hasContent(t){return this._data[t*dt+0]&4194303}getCodePoint(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*dt+0]&2097152}getString(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t]:i&2097151?js(i&2097151):""}isProtected(t){return this._data[t*dt+2]&536870912}loadCell(t,i){return Jc=t*dt,i.content=this._data[Jc+0],i.fg=this._data[Jc+1],i.bg=this._data[Jc+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*dt+0]=i.content,this._data[t*dt+1]=i.fg,this._data[t*dt+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*dt+0]=i|s<<22,this._data[t*dt+1]=a.fg,this._data[t*dt+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*dt+0];a&2097152?this._combined[t]+=js(i):a&2097151?(this._combined[t]=js(a&2097151)+js(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*dt+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*sf=0;--t)if(this._data[t*dt+0]&4194303)return t+(this._data[t*dt+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*dt+0]&4194303||this._data[t*dt+2]&50331648)return t+(this._data[t*dt+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let d=0;d=i&&(this._combined[d-i+s]=t._combined[d])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function P2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(A>x||_[A].getTrimmedLength()===0);A--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function I2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cko(e,d,t)).reduce((p,d)=>p+d),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let d=e[c].getWidth(o-1)===2;d&&o--;let _=d?i-1:i;s.push(_),h+=_}return s}function ko(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var o0=class c0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=c0._nextId++,this._onDispose=this.register(new ke),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),aa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};o0._nextId=1;var $2=o0,Ri={},na=Ri.B;Ri[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Ri.A={"#":"£"};Ri.B=void 0;Ri[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Ri.C=Ri[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Ri.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Ri.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Ri.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Ri.E=Ri[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Ri.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Ri.H=Ri[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Lb=4294967295,Ob=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=wi.clone(),this.savedCharset=na,this.markers=[],this._nullCell=sr.fromCharData([0,Ey,1,0]),this._whitespaceCell=sr.fromCharData([0,Rs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Nu,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new wu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new wu),this._whitespaceCell}getBlankLine(e,t){return new go(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eLb?Lb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=wi);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(wi),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new go(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=P2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(wi),i);if(s.length>0){let a=I2(this.lines,s);H2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(wi),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let P=this.ybase+this.y;if(P>=c&&P0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let y=_.length-1,N=_[y];N===0&&(y--,N=_[y]);let A=p.length-x-1,E=d;for(;A>=0;){let P=Math.min(E,N);if(p[y]===void 0)break;if(p[y].copyCellsFrom(p[A],E-P,N-P,P,!0),N-=P,N===0&&(y--,N=_[y]),E-=P,E===0){A--;let J=Math.max(A,0);E=ko(p,J,this._cols)}}for(let P=0;P0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>d+b){for(let A=x.newLines.length-1;A>=0;A--)this.lines.set(N--,x.newLines[A]);N++,c.push({index:d+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[d--]);let v=0;for(let N=c.length-1;N>=0;N--)c[N].index+=v,this.lines.onInsertEmitter.fire(c[N]),v+=c[N].amount;let y=Math.max(0,p+o-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},F2=class extends ft{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ke),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ob(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ob(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},u0=2,h0=1,fp=class extends ft{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,u0),this.rows=Math.max(e.rawOptions.rows||0,h0),this.buffers=this._register(new F2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};fp=oi([Me(0,pn)],fp);var Va={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Eu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},q2=["normal","bold","100","200","300","400","500","600","700","800","900"],W2=class extends ft{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...Va};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Jt(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Va[e]),!G2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Va[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=q2.includes(t)?t:Va[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function G2(e){return e==="block"||e==="underline"||e==="bar"}function xo(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&xo(e[s],t-1);return i}var zb=Object.freeze({insertMode:!1}),Pb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ke),this.onData=this._onData.event,this._onUserInput=this._register(new ke),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ke),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=xo(zb),this.decPrivateModes=xo(Pb)}reset(){this.modes=xo(zb),this.decPrivateModes=xo(Pb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pp=oi([Me(0,fn),Me(1,Ry),Me(2,pn)],pp);var Ib={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function af(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var lf=String.fromCharCode,Hb={DEFAULT:e=>{let t=[af(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${lf(t[0])}${lf(t[1])}${lf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.x};${e.y}${t}`}},mp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ke),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Ib))this.addProtocol(s,Ib[s]);for(let s of Object.keys(Hb))this.addEncoding(s,Hb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mp=oi([Me(0,fn),Me(1,ca),Me(2,pn)],mp);var of=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Y2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],ji;function K2(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ra.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ra.createPropertyValue(0,i,s)}},ra=class gu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new V2;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let d=t.charCodeAt(o);56320<=d&&d<=57343?c=(c-55296)*1024+d-56320+65536:i+=this.wcwidth(d)}let h=this.charProperties(c,s),p=gu.extractWidth(h);gu.extractShouldJoin(h)&&(p-=gu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},X2=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ub(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ao=2147483647,Z2=256,d0=class gp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>Z2)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new gp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ao?ao:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>ao?ao:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,ao):t}},lo=[],Q2=class{constructor(){this._state=0,this._active=lo,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=lo}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=lo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lo,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=lo,this._id=-1,this._state=0}}},Hn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},oo=[],J2=class{constructor(){this._handlers=Object.create(null),this._active=oo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=oo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=oo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||oo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=oo,this._ident=0}},_o=new d0;_o.addParam(0);var $b=class{constructor(e){this._handler=e,this._data="",this._params=_o,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_o,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=_o,this._data="",this._hitLimit=!1,i));return this._params=_o,this._data="",this._hitLimit=!1,t}},eE=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(nr,0,2,0),e.add(nr,8,5,8),e.add(nr,6,0,6),e.add(nr,11,0,11),e.add(nr,13,13,13),e})(),iE=class extends ft{constructor(e=tE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new d0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Jt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Q2),this._dcsParser=this._register(new J2),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[d](this._params),c!==!0);d--)if(c instanceof Promise)return this._preserveStack(3,p,d,a,h),c;d<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function cf(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function sE(e,t=16){let[i,s,a]=e;return`rgb:${cf(i,t)}/${cf(s,t)}/${cf(a,t)}`}var aE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ns=131072,qb=10;function Wb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Gb=5e3,Yb=0,lE=class extends ft{constructor(e,t,i,s,a,o,c,h,p=new iE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new EC,this._utf8Decoder=new NC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone(),this._onRequestBell=this._register(new ke),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ke),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ke),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ke),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ke),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ke),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ke),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ke),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ke),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new xp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(d=>this._activeBuffer=d.activeBuffer)),this._parser.setCsiHandlerFallback((d,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(d),params:_.toArray()})}),this._parser.setEscHandlerFallback(d=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(d)})}),this._parser.setExecuteHandlerFallback(d=>{this._logService.debug("Unknown EXECUTE code: ",{code:d})}),this._parser.setOscHandlerFallback((d,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:d,action:_,data:x})}),this._parser.setDcsHandlerFallback((d,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(d),action:_,payload:x})}),this._parser.setPrintHandler((d,_,x)=>this.print(d,_,x)),this._parser.registerCsiHandler({final:"@"},d=>this.insertChars(d)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},d=>this.scrollLeft(d)),this._parser.registerCsiHandler({final:"A"},d=>this.cursorUp(d)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},d=>this.scrollRight(d)),this._parser.registerCsiHandler({final:"B"},d=>this.cursorDown(d)),this._parser.registerCsiHandler({final:"C"},d=>this.cursorForward(d)),this._parser.registerCsiHandler({final:"D"},d=>this.cursorBackward(d)),this._parser.registerCsiHandler({final:"E"},d=>this.cursorNextLine(d)),this._parser.registerCsiHandler({final:"F"},d=>this.cursorPrecedingLine(d)),this._parser.registerCsiHandler({final:"G"},d=>this.cursorCharAbsolute(d)),this._parser.registerCsiHandler({final:"H"},d=>this.cursorPosition(d)),this._parser.registerCsiHandler({final:"I"},d=>this.cursorForwardTab(d)),this._parser.registerCsiHandler({final:"J"},d=>this.eraseInDisplay(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},d=>this.eraseInDisplay(d,!0)),this._parser.registerCsiHandler({final:"K"},d=>this.eraseInLine(d,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},d=>this.eraseInLine(d,!0)),this._parser.registerCsiHandler({final:"L"},d=>this.insertLines(d)),this._parser.registerCsiHandler({final:"M"},d=>this.deleteLines(d)),this._parser.registerCsiHandler({final:"P"},d=>this.deleteChars(d)),this._parser.registerCsiHandler({final:"S"},d=>this.scrollUp(d)),this._parser.registerCsiHandler({final:"T"},d=>this.scrollDown(d)),this._parser.registerCsiHandler({final:"X"},d=>this.eraseChars(d)),this._parser.registerCsiHandler({final:"Z"},d=>this.cursorBackwardTab(d)),this._parser.registerCsiHandler({final:"`"},d=>this.charPosAbsolute(d)),this._parser.registerCsiHandler({final:"a"},d=>this.hPositionRelative(d)),this._parser.registerCsiHandler({final:"b"},d=>this.repeatPrecedingCharacter(d)),this._parser.registerCsiHandler({final:"c"},d=>this.sendDeviceAttributesPrimary(d)),this._parser.registerCsiHandler({prefix:">",final:"c"},d=>this.sendDeviceAttributesSecondary(d)),this._parser.registerCsiHandler({final:"d"},d=>this.linePosAbsolute(d)),this._parser.registerCsiHandler({final:"e"},d=>this.vPositionRelative(d)),this._parser.registerCsiHandler({final:"f"},d=>this.hVPosition(d)),this._parser.registerCsiHandler({final:"g"},d=>this.tabClear(d)),this._parser.registerCsiHandler({final:"h"},d=>this.setMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"h"},d=>this.setModePrivate(d)),this._parser.registerCsiHandler({final:"l"},d=>this.resetMode(d)),this._parser.registerCsiHandler({prefix:"?",final:"l"},d=>this.resetModePrivate(d)),this._parser.registerCsiHandler({final:"m"},d=>this.charAttributes(d)),this._parser.registerCsiHandler({final:"n"},d=>this.deviceStatus(d)),this._parser.registerCsiHandler({prefix:"?",final:"n"},d=>this.deviceStatusPrivate(d)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},d=>this.softReset(d)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},d=>this.setCursorStyle(d)),this._parser.registerCsiHandler({final:"r"},d=>this.setScrollRegion(d)),this._parser.registerCsiHandler({final:"s"},d=>this.saveCursor(d)),this._parser.registerCsiHandler({final:"t"},d=>this.windowOptions(d)),this._parser.registerCsiHandler({final:"u"},d=>this.restoreCursor(d)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},d=>this.insertColumns(d)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},d=>this.deleteColumns(d)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},d=>this.selectProtected(d)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},d=>this.requestMode(d,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},d=>this.requestMode(d,!1)),this._parser.setExecuteHandler(pe.BEL,()=>this.bell()),this._parser.setExecuteHandler(pe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(pe.BS,()=>this.backspace()),this._parser.setExecuteHandler(pe.HT,()=>this.tab()),this._parser.setExecuteHandler(pe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(pe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(pu.IND,()=>this.index()),this._parser.setExecuteHandler(pu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(pu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Hn(d=>(this.setTitle(d),this.setIconName(d),!0))),this._parser.registerOscHandler(1,new Hn(d=>this.setIconName(d))),this._parser.registerOscHandler(2,new Hn(d=>this.setTitle(d))),this._parser.registerOscHandler(4,new Hn(d=>this.setOrReportIndexedColor(d))),this._parser.registerOscHandler(8,new Hn(d=>this.setHyperlink(d))),this._parser.registerOscHandler(10,new Hn(d=>this.setOrReportFgColor(d))),this._parser.registerOscHandler(11,new Hn(d=>this.setOrReportBgColor(d))),this._parser.registerOscHandler(12,new Hn(d=>this.setOrReportCursorColor(d))),this._parser.registerOscHandler(104,new Hn(d=>this.restoreIndexedColor(d))),this._parser.registerOscHandler(110,new Hn(d=>this.restoreFgColor(d))),this._parser.registerOscHandler(111,new Hn(d=>this.restoreBgColor(d))),this._parser.registerOscHandler(112,new Hn(d=>this.restoreCursorColor(d))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let d in Ri)this._parser.registerEscHandler({intermediates:"(",final:d},()=>this.selectCharset("("+d)),this._parser.registerEscHandler({intermediates:")",final:d},()=>this.selectCharset(")"+d)),this._parser.registerEscHandler({intermediates:"*",final:d},()=>this.selectCharset("*"+d)),this._parser.registerEscHandler({intermediates:"+",final:d},()=>this.selectCharset("+"+d)),this._parser.registerEscHandler({intermediates:"-",final:d},()=>this.selectCharset("-"+d)),this._parser.registerEscHandler({intermediates:".",final:d},()=>this.selectCharset("."+d)),this._parser.registerEscHandler({intermediates:"/",final:d},()=>this.selectCharset("/"+d));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(d=>(this._logService.error("Parsing error: ",d),d)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new $b((d,_)=>this.requestStatusString(d,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Gb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Gb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ns&&(o=this._parseStack.position+Ns)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,d=>String.fromCharCode(d)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(d=>d.charCodeAt(0)):e),this._parseBuffer.lengthNs)for(let d=o;d0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,D=this._activeBuffer.x-A;for(this._activeBuffer.x=A,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),A>0&&x instanceof go&&x.copyCellsFrom(E,D,0,A,!1);D=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(d&&(x.insertCells(this._activeBuffer.x,a-A,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Wb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new $b(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Hn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let d=1;d0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(pe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(pe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(pe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(pe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(pe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(N[N.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",N[N.SET=1]="SET",N[N.RESET=2]="RESET",N[N.PERMANENTLY_SET=3]="PERMANENTLY_SET",N[N.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:d,alt:_}=h,x=this._optionsService.rawOptions,b=(N,A)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${A}$y`),!0),v=N=>N?1:2,y=e.params[0];return t?y===2?b(y,4):y===4?b(y,v(c.modes.insertMode)):y===12?b(y,3):y===20?b(y,v(x.convertEol)):b(y,0):y===1?b(y,v(s.applicationCursorKeys)):y===3?b(y,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):y===6?b(y,v(s.origin)):y===7?b(y,v(s.wraparound)):y===8?b(y,3):y===9?b(y,v(a==="X10")):y===12?b(y,v(x.cursorBlink)):y===25?b(y,v(!c.isCursorHidden)):y===45?b(y,v(s.reverseWraparound)):y===66?b(y,v(s.applicationKeypad)):y===67?b(y,4):y===1e3?b(y,v(a==="VT200")):y===1002?b(y,v(a==="DRAG")):y===1003?b(y,v(a==="ANY")):y===1004?b(y,v(s.sendFocus)):y===1005?b(y,4):y===1006?b(y,v(o==="SGR")):y===1015?b(y,4):y===1016?b(y,v(o==="SGR_PIXELS")):y===1048?b(y,1):y===47||y===1047||y===1049?b(y,v(d===_)):y===2004?b(y,v(s.bracketedPasteMode)):y===2026?b(y,v(s.synchronizedOutput)):b(y,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ao.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=wi.fg,e.bg=wi.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=wi.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=wi.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=wi.fg&16777215,s.bg&=-67108864,s.bg|=wi.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${pe.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=wi.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Wb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>qb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>qb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Kb(o))if(a==="?")t.push({type:0,index:o});else{let c=Fb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Fb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=wi.clone(),this._eraseAttrDataInternal=wi.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},xp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Yb=e,e=t,t=Yb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};xp=oi([Me(0,fn)],xp);function Kb(e){return 0<=e&&e<256}var oE=5e7,Vb=12,cE=50,uE=class extends ft{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>oE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=Vb?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Vb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>cE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},_p=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};_p=oi([Me(0,fn)],_p);var Xb=!1,hE=class extends ft{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new sl),this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onData=this._register(new ke),this.onData=this._onData.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ke),this._instantiationService=new L2,this.optionsService=this._register(new W2(e)),this._instantiationService.setService(pn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fp)),this._instantiationService.setService(fn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(dp)),this._instantiationService.setService(Ry,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pp)),this._instantiationService.setService(ca,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(Ay,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ra)),this._instantiationService.setService(RC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(X2),this._instantiationService.setService(AC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_p),this._instantiationService.setService(My,this._oscLinkService),this._inputHandler=this._register(new lE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Vi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Vi.forward(this._bufferService.onResize,this._onResize)),this._register(Vi.forward(this.coreService.onData,this._onData)),this._register(Vi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new uE((t,i)=>this._inputHandler.parse(t,i))),this._register(Vi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ke),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Xb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Xb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,u0),t=Math.max(t,h0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ub.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ub(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Jt(()=>{for(let t of e)t.dispose()})}}},dE={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function fE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":pe.DEL,e.altKey&&(a.key=pe.ESC+a.key);break;case 9:if(e.shiftKey){a.key=pe.ESC+"[Z";break}a.key=pe.HT,a.cancel=!0;break;case 13:a.key=e.altKey?pe.ESC+pe.CR:pe.CR,a.cancel=!0;break;case 27:a.key=pe.ESC,e.altKey&&(a.key=pe.ESC+pe.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"D":t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"C":t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"A":t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"B":t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=pe.ESC+"[2~");break;case 46:o?a.key=pe.ESC+"[3;"+(o+1)+"~":a.key=pe.ESC+"[3~";break;case 36:o?a.key=pe.ESC+"[1;"+(o+1)+"H":t?a.key=pe.ESC+"OH":a.key=pe.ESC+"[H";break;case 35:o?a.key=pe.ESC+"[1;"+(o+1)+"F":t?a.key=pe.ESC+"OF":a.key=pe.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=pe.ESC+"[5;"+(o+1)+"~":a.key=pe.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=pe.ESC+"[6;"+(o+1)+"~":a.key=pe.ESC+"[6~";break;case 112:o?a.key=pe.ESC+"[1;"+(o+1)+"P":a.key=pe.ESC+"OP";break;case 113:o?a.key=pe.ESC+"[1;"+(o+1)+"Q":a.key=pe.ESC+"OQ";break;case 114:o?a.key=pe.ESC+"[1;"+(o+1)+"R":a.key=pe.ESC+"OR";break;case 115:o?a.key=pe.ESC+"[1;"+(o+1)+"S":a.key=pe.ESC+"OS";break;case 116:o?a.key=pe.ESC+"[15;"+(o+1)+"~":a.key=pe.ESC+"[15~";break;case 117:o?a.key=pe.ESC+"[17;"+(o+1)+"~":a.key=pe.ESC+"[17~";break;case 118:o?a.key=pe.ESC+"[18;"+(o+1)+"~":a.key=pe.ESC+"[18~";break;case 119:o?a.key=pe.ESC+"[19;"+(o+1)+"~":a.key=pe.ESC+"[19~";break;case 120:o?a.key=pe.ESC+"[20;"+(o+1)+"~":a.key=pe.ESC+"[20~";break;case 121:o?a.key=pe.ESC+"[21;"+(o+1)+"~":a.key=pe.ESC+"[21~";break;case 122:o?a.key=pe.ESC+"[23;"+(o+1)+"~":a.key=pe.ESC+"[23~";break;case 123:o?a.key=pe.ESC+"[24;"+(o+1)+"~":a.key=pe.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=pe.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=pe.DEL:e.keyCode===219?a.key=pe.ESC:e.keyCode===220?a.key=pe.FS:e.keyCode===221&&(a.key=pe.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=dE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=pe.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,d=String.fromCharCode(p);e.shiftKey&&(d=d.toUpperCase()),a.key=pe.ESC+d}else if(e.keyCode===32)a.key=pe.ESC+(e.ctrlKey?pe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=pe.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=pe.US),e.key==="@"&&(a.key=pe.NUL));break}return a}var di=0,pE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Nu,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Nu,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(di=this._search(t),di===-1)||this._getKey(this._array[di])!==t)return!1;do if(this._array[di]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(di),!0;while(++dia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(di=this._search(e),!(di<0||di>=this._array.length)&&this._getKey(this._array[di])===e))do yield this._array[di];while(++di=this._array.length)&&this._getKey(this._array[di])===e))do t(this._array[di]);while(++di=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},uf=0,Zb=0,mE=class extends ft{constructor(){super(),this._decorations=new pE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ke),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ke),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Jt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new gE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{uf=a.options.x??0,Zb=uf+(a.options.width??1),e>=uf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Qb=20,Tu=class extends ft{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new _E(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ye(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Jt(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Qb+1&&(this._liveRegion.textContent+=Pf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),d=this._rowElements[a];d&&(h.length===0?(d.textContent=" ",this._rowColumns.set(d,[0,1])):(d.textContent=h,this._rowColumns.set(d,c)),d.setAttribute("aria-posinset",p),d.setAttribute("aria-setsize",s),this._alignRowWidth(d))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:d})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=d=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ye(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ye(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ye(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ye(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var d,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(d=this._activeProviderReplies)==null||d.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let d=h;d<=p;d++){if(i.has(d)){a.splice(o--,1);break}i.add(d)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&bE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};bp=oi([Me(1,Ip),Me(2,Jr),Me(3,fn),Me(4,By)],bp);function bE(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var vE=class extends hE{constructor(e={}){super(e),this._linkifier=this._register(new sl),this.browser=Jy,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new sl),this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ke),this.onKey=this._onKey.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ke),this.onBell=this._onBell.event,this._onFocus=this._register(new ke),this._onBlur=this._register(new ke),this._onA11yCharEmitter=this._register(new ke),this._onA11yTabEmitter=this._register(new ke),this._onWillOpen=this._register(new ke),this._setup(),this._decorationService=this._instantiationService.createInstance(mE),this._instantiationService.setService(Ro,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(c2),this._instantiationService.setService(By,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Hf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Vi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Vi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Vi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Vi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Jt(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Xt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${sE(a)}${Zy.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ci.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ci.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ye(this.element,"copy",t=>{this.hasSelection()&&CC(t,this._selectionService)}));let e=t=>kC(t,this.textarea,this.coreService,this.optionsService);this._register(Ye(this.textarea,"paste",e)),this._register(Ye(this.element,"paste",e)),e0?this._register(Ye(this.element,"mousedown",t=>{t.button===2&&ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ye(this.element,"contextmenu",t=>{ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Yp&&this._register(Ye(this.element,"auxclick",t=>{t.button===1&&ky(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ye(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ye(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ye(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ye(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ye(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ye(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ye(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ye(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",zf.get()),n0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(l2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Qr,this._coreBrowserService),this._register(Ye(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ye(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(lp,this._document,this._helperContainer),this._instantiationService.setService(Lu,this._charSizeService),this._themeService=this._instantiationService.createInstance(hp),this._instantiationService.setService(ol,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ku),this._instantiationService.setService(Dy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cp,this.rows,this.screenElement)),this._instantiationService.setService(Jr,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(rp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(op),this._instantiationService.setService(Ip,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(bp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ip,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(up,this.element,this.screenElement,s)),this._instantiationService.setService(DC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(Vi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(np,this.screenElement)),this._register(Ye(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ap,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var d,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let y=o.deltaY;if(y===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(d=e._renderService)==null?void 0:d.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=y<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ye(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ye(t,"wheel",o=>{var c,h,p,d,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(d=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:d.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Cy(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=fE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===pe.ETX||i.key===pe.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(yE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new sr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Jb=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new wE(t)}getNullCell(){return new sr}},CE=class extends ft{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new Jb(this._core.buffers.normal,"normal"),this._alternate=new Jb(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},kE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},EE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},NE=["cols","rows"],yr=0,TE=class extends ft{constructor(e){super(),this._core=this._register(new vE(e)),this._addonManager=this._register(new SE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(NE.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new kE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new EE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new CE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return zf.get()},set promptLabel(e){zf.set(e)},get tooMuchOutput(){return Pf.get()},set tooMuchOutput(e){Pf.set(e)}}}_verifyIntegers(...e){for(yr of e)if(yr===1/0||isNaN(yr)||yr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(yr of e)if(yr&&(yr===1/0||isNaN(yr)||yr%1!==0||yr<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * 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 jE=2,AE=1,RE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var x;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((x=this._terminal.options.overviewRuler)==null?void 0:x.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,d=s-h,_=a-p-t;return{cols:Math.max(jE,Math.floor(_/e.css.cell.width)),rows:Math.max(AE,Math.floor(d/e.css.cell.height))}}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * 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 zi=0,Pi=0,Ii=0,li=0,tn;(e=>{function t(a,o,c,h){return h!==void 0?`#${Js(a)}${Js(o)}${Js(c)}${Js(h)}`:`#${Js(a)}${Js(o)}${Js(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(tn||(tn={}));var ME;(e=>{function t(p,d){if(li=(d.rgba&255)/255,li===1)return{css:d.css,rgba:d.rgba};let _=d.rgba>>24&255,x=d.rgba>>16&255,b=d.rgba>>8&255,v=p.rgba>>24&255,y=p.rgba>>16&255,N=p.rgba>>8&255;zi=v+Math.round((_-v)*li),Pi=y+Math.round((x-y)*li),Ii=N+Math.round((b-N)*li);let A=tn.toCss(zi,Pi,Ii),E=tn.toRgba(zi,Pi,Ii);return{css:A,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,d,_){let x=xu.ensureContrastRatio(p.rgba,d.rgba,_);if(x)return tn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let d=(p.rgba|255)>>>0;return[zi,Pi,Ii]=xu.toChannels(d),{css:tn.toCss(zi,Pi,Ii),rgba:d}}e.opaque=a;function o(p,d){return li=Math.round(d*255),[zi,Pi,Ii]=xu.toChannels(p.rgba),{css:tn.toCss(zi,Pi,Ii,li),rgba:tn.toRgba(zi,Pi,Ii,li)}}e.opacity=o;function c(p,d){return li=p.rgba&255,o(p,li*d/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ME||(ME={}));var Yi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return zi=parseInt(a.slice(1,2).repeat(2),16),Pi=parseInt(a.slice(2,3).repeat(2),16),Ii=parseInt(a.slice(3,4).repeat(2),16),tn.toColor(zi,Pi,Ii);case 5:return zi=parseInt(a.slice(1,2).repeat(2),16),Pi=parseInt(a.slice(2,3).repeat(2),16),Ii=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),tn.toColor(zi,Pi,Ii,li);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return zi=parseInt(o[1]),Pi=parseInt(o[2]),Ii=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),tn.toColor(zi,Pi,Ii,li);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[zi,Pi,Ii,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:tn.toRgba(zi,Pi,Ii,li),css:a}}e.toColor=s})(Yi||(Yi={}));var hn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return d*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var xu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,d=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return zi=x+Math.round((p-x)*li),Pi=b+Math.round((d-b)*li),Ii=v+Math.round((_-v)*li),tn.toRgba(zi,Pi,Ii)}e.blend=t;function i(c,h,p){let d=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Kr(d,_)>8));if(y>8));return y>A?v:N}return v}let x=a(c,h,p),b=Kr(d,hn.relativeLuminance(x>>8));if(b>8));return b>y?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));return(b<<24|v<<16|y<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let d=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,y=h>>8&255,N=Kr(hn.relativeLuminance2(b,v,y),hn.relativeLuminance2(d,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(xu||(xu={}));function Js(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Kr(e,t){return e{let e=[Yi.toColor("#2e3436"),Yi.toColor("#cc0000"),Yi.toColor("#4e9a06"),Yi.toColor("#c4a000"),Yi.toColor("#3465a4"),Yi.toColor("#75507b"),Yi.toColor("#06989a"),Yi.toColor("#d3d7cf"),Yi.toColor("#555753"),Yi.toColor("#ef2929"),Yi.toColor("#8ae234"),Yi.toColor("#fce94f"),Yi.toColor("#729fcf"),Yi.toColor("#ad7fa8"),Yi.toColor("#34e2e2"),Yi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:tn.toCss(s,a,o),rgba:tn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:tn.toCss(s,s,s),rgba:tn.toRgba(s,s,s)})}return e})());function ev(e,t,i){return Math.max(t,Math.min(e,i))}function BE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var f0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let d=o;d<=c;d++){let _=this._buffer.getLine(d);if(_){let x=d===e.start.y?h:0,b=d===e.end.y?p:_.length;for(let v=x;v0&&!Vr(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r -`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),d=p.getWidth()>1,_=!1;(p.getChars()&&d?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&Vr(c,p)&&(_=!0),d&&(h.getChars()||h.getWidth()===0)&&Vr(c,p)&&Vr(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!p0(e,t),a=!Vr(e,t),o=!m0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!Vr(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{d>0?i+=`\x1B[${d}C`:d<0&&(i+=`\x1B[${-d}D`)};h&&((d=>{d>0?i+=`\x1B[${d}B`:d<0&&(i+=`\x1B[${-d}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},OE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:ev(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new LE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new zE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,d=t.scrollback,_=d===void 0?p:ev(d+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},zE=class extends f0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=DE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!p0(e,t),a=!Vr(e,t),o=!m0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"":""),a?this._currentRow+=" ":this._currentRow+=BE(e.getChars())}_serializeString(){return this._htmlContent}};const PE="__OWS_FRESH_SESSION__",Xa="[REDACTED]",IE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${Xa}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${Xa}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${Xa}`]];function tv(e){let t=e;for(const[i,s]of IE)t=t.replace(i,s);return t}const iv="codex features enable image_generation";function HE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const UE={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},$E="plotlink-terminal",FE=1,Ds="scrollback",nv=10*1024*1024;function Kp(){return new Promise((e,t)=>{const i=indexedDB.open($E,FE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ds)||s.createObjectStore(Ds)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Za(e,t){const i=t.length>nv?t.slice(-nv):t,s=await Kp();return new Promise((a,o)=>{const c=s.transaction(Ds,"readwrite");c.objectStore(Ds).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function qE(e){const t=await Kp();return new Promise((i,s)=>{const o=t.transaction(Ds,"readonly").objectStore(Ds).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function hf(e){const t=await Kp();return new Promise((i,s)=>{const a=t.transaction(Ds,"readwrite");a.objectStore(Ds).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ai=new Map;function WE({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:d,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const y=w.useRef(null),N=w.useRef(i),[A,E]=w.useState([]),[D,P]=w.useState(new Set),[J,q]=w.useState(null),[L,Z]=w.useState(null),[he,ye]=w.useState(!1),[U,re]=w.useState(!1),W=HE(x,_),G=!!b,X=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const I=w.useCallback($=>{var be;const{width:ue}=$.container.getBoundingClientRect();if(!(ue<50))try{$.fit.fit(),((be=$.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&$.ws.send(JSON.stringify({type:"resize",cols:$.term.cols,rows:$.term.rows}))}catch{}},[]),j=w.useCallback($=>{for(const[ue,be]of Ai)be.container.style.display=ue===$?"block":"none";if($){const ue=Ai.get($);ue&&setTimeout(()=>I(ue),50)}},[I]),O=w.useRef({});w.useEffect(()=>{O.current=p||{}},[p]);const B=w.useRef({});w.useEffect(()=>{B.current=d||{}},[d]);const xe=w.useCallback(($,ue,be)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",Ee=O.current[$]?"&bypass=true":"",Be=B.current[$],je=Be?`&provider=${encodeURIComponent(Be)}`:"",Ze=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent($)}&token=${e}&resume=${be}${Ee}${je}`);Ze.onopen=()=>{ue.connected=!0,ue._retried=!1,P(tt=>{const pt=new Set(tt);return pt.delete($),pt}),Ze.send(JSON.stringify({type:"resize",cols:ue.term.cols,rows:ue.term.rows}))};let Ce=!0;Ze.onmessage=tt=>{if(Ce&&(Ce=!1,typeof tt.data=="string"&&tt.data===PE)){ue.term.reset(),hf($).catch(()=>{});return}ue.term.write(typeof tt.data=="string"?tv(tt.data):tt.data)},Ze.onclose=tt=>{if(ue.connected=!1,ue.ws===Ze){ue.ws=null;try{const pt=ue.serialize.serialize();Za($,pt).catch(()=>{})}catch{}if(tt.code===4e3&&!ue._retried){ue._retried=!0,ue.term.write(`\r -\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),X.current($,ue,!1);return}P(pt=>new Set(pt).add($))}},ue.term.onData(tt=>{Ze.readyState===WebSocket.OPEN&&Ze.send(tt)}),ue.ws=Ze},[e]);w.useEffect(()=>{X.current=xe},[xe]);const T=w.useCallback(async($,ue)=>{if(!y.current||Ai.has($))return;const{resume:be=!1,autoConnect:De=!0}=ue??{},Ee=document.createElement("div");Ee.style.width="100%",Ee.style.height="100%",Ee.style.display="none",Ee.style.paddingLeft="10px",Ee.style.boxSizing="border-box",y.current.appendChild(Ee);const Be=new TE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:UE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),je=new RE,Ze=new OE;Be.loadAddon(je),Be.loadAddon(Ze),Be.open(Ee);const Ce={term:Be,fit:je,serialize:Ze,ws:null,container:Ee,observer:null,connected:!1},tt=new ResizeObserver(()=>{var Ge;const{width:pt}=Ee.getBoundingClientRect();if(!(pt<50))try{je.fit(),((Ge=Ce.ws)==null?void 0:Ge.readyState)===WebSocket.OPEN&&Ce.ws.send(JSON.stringify({type:"resize",cols:Be.cols,rows:Be.rows}))}catch{}});tt.observe(Ee),Ce.observer=tt,Ai.set($,Ce),E(pt=>[...pt,$]);try{const pt=await qE($);if(pt){const Ge=tv(pt);Be.write(Ge),Ge!==pt&&Za($,Ge).catch(()=>{})}}catch{}De?xe($,Ce,be):P(pt=>new Set(pt).add($)),setTimeout(()=>I(Ce),50)},[xe,I]),R=w.useCallback(async($,ue)=>{const be=Ai.get($);be&&(be.ws&&(be.ws.close(),be.ws=null),ue||(await N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),be.term.clear()),xe($,be,ue))},[xe]),Y=w.useCallback($=>{const ue=Ai.get($);if(ue){try{const be=ue.serialize.serialize();Za($,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),Ai.delete($),E(be=>be.filter(De=>De!==$)),P(be=>{const De=new Set(be);return De.delete($),De}),i(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),a==null||a($)}},[i,a]),C=w.useCallback($=>{var be;const ue=Ai.get($);ue&&(((be=ue.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&ue.ws.send(`exit -`),hf($).catch(()=>{}),ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),Ai.delete($),E(De=>De.filter(Ee=>Ee!==$)),P(De=>{const Ee=new Set(De);return Ee.delete($),Ee}),i(`/api/terminal/${encodeURIComponent($)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a($))},[i,a]),se=w.useCallback(async($,ue,be)=>{const De=Ai.get($);if(!De||Ai.has(ue)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:$,newName:ue,...be??{}})})).ok)return!1;Ai.delete($),Ai.set(ue,De);try{const Be=De.serialize.serialize();await hf($),await Za(ue,Be)}catch{}return E(Be=>Be.map(je=>je===$?ue:je)),P(Be=>{if(!Be.has($))return Be;const je=new Set(Be);return je.delete($),je.add(ue),je}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(ue)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),X.current(ue,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=se),()=>{h&&(h.current=null)}),[h,se]),w.useEffect(()=>{if(t){if(W){j(null);return}if(G){j(null);return}Ai.has(t)?j(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then($=>$.ok?$.json():null).then($=>{if(!Ai.has(t)){const ue=($==null?void 0:$.sessionId)&&!($!=null&&$.running);T(t,{autoConnect:!ue}),j(t)}}).catch(()=>{Ai.has(t)||(T(t),j(t))})}},[t,T,j,W,G]),w.useEffect(()=>{const $=setInterval(()=>{for(const[ue,be]of Ai)if(be.connected)try{const De=be.serialize.serialize();Za(ue,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval($)},[]),w.useEffect(()=>()=>{for(const[$,ue]of Ai){try{const be=ue.serialize.serialize();Za($,be).catch(()=>{})}catch{}ue.observer.disconnect(),ue.ws&&ue.ws.close(),ue.term.dispose(),ue.container.remove(),N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{})}Ai.clear()},[]);const te=t?D.has(t):!1,oe=A.length===0;return f.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&f.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[A.map($=>f.jsxs("div",{onClick:()=>s==null?void 0:s($),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${$===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[f.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${D.has($)?"bg-amber-500":$===t?"bg-green-600":"bg-muted/50"}`}),f.jsx("span",{className:`truncate max-w-[120px] ${$.startsWith("_new_")?"italic":""}`,children:$.startsWith("_new_")?"Untitled":$}),f.jsx("button",{onClick:ue=>{ue.stopPropagation(),$.startsWith("_new_")?q($):Y($)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},$)),t!=null&&t.startsWith("_new_")?f.jsx("button",{onClick:()=>q(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?f.jsx("button",{onClick:()=>Z(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),f.jsxs("div",{className:"relative flex-1 min-h-0",children:[f.jsx("div",{ref:y,className:"h-full"}),oe&&!W&&!G&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),f.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),W&&f.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),f.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?f.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Su(_)?f.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[zp," Then reopen this story."]}):f.jsxs("div",{className:"space-y-1",children:[f.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:iv}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(iv),ye(!0),setTimeout(()=>ye(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:he?"Copied!":"Copy"})]})]})]})}),G&&!W&&f.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),f.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),f.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),f.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:U,onClick:async()=>{if(!U){re(!0);try{await(v==null?void 0:v())}finally{re(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:U?"Setting…":"Set this story's provider to Codex"})]})}),J&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),f.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:()=>{const $=J;q(null),C($)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),L&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[f.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),f.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),f.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f.jsx("button",{onClick:()=>Z(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),f.jsx("button",{onClick:async()=>{const $=L;Z(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$})})).ok&&(Y($),o==null||o($))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),te&&t&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>R(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),f.jsx("button",{onClick:()=>R(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),f.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function GE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const YE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,KE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,VE={};function rv(e,t){return(VE.jsx?KE:YE).test(e)}const XE=/[ \t\n\f\r]/g;function ZE(e){return typeof e=="object"?e.type==="text"?sv(e.value):!1:sv(e)}function sv(e){return e.replace(XE,"")===""}class Bo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Bo.prototype.normal={};Bo.prototype.property={};Bo.prototype.space=void 0;function g0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Bo(i,s,t)}function vp(e){return e.toLowerCase()}class Nn{constructor(t,i){this.attribute=i,this.property=t}}Nn.prototype.attribute="";Nn.prototype.booleanish=!1;Nn.prototype.boolean=!1;Nn.prototype.commaOrSpaceSeparated=!1;Nn.prototype.commaSeparated=!1;Nn.prototype.defined=!1;Nn.prototype.mustUseProperty=!1;Nn.prototype.number=!1;Nn.prototype.overloadedBoolean=!1;Nn.prototype.property="";Nn.prototype.spaceSeparated=!1;Nn.prototype.space=void 0;let QE=0;const ot=ua(),Si=ua(),yp=ua(),ve=ua(),Wt=ua(),il=ua(),Un=ua();function ua(){return 2**++QE}const Sp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Si,commaOrSpaceSeparated:Un,commaSeparated:il,number:ve,overloadedBoolean:yp,spaceSeparated:Wt},Symbol.toStringTag,{value:"Module"})),df=Object.keys(Sp);class Vp extends Nn{constructor(t,i,s,a){let o=-1;if(super(t,i),av(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&nN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(lv,aN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!lv.test(o)){let c=o.replace(iN,sN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Vp}return new a(s,t)}function sN(e){return"-"+e.toLowerCase()}function aN(e){return e.charAt(1).toUpperCase()}const lN=g0([x0,JE,v0,y0,S0],"html"),Xp=g0([x0,eN,v0,y0,S0],"svg");function oN(e){return e.join(" ").trim()}var Qa={},ff,ov;function cN(){if(ov)return ff;ov=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` -`,d="/",_="*",x="",b="comment",v="declaration";function y(A,E){if(typeof A!="string")throw new TypeError("First argument must be a string");if(!A)return[];E=E||{};var D=1,P=1;function J(X){var I=X.match(t);I&&(D+=I.length);var j=X.lastIndexOf(p);P=~j?X.length-j:P+X.length}function q(){var X={line:D,column:P};return function(I){return I.position=new L(X),ye(),I}}function L(X){this.start=X,this.end={line:D,column:P},this.source=E.source}L.prototype.content=A;function Z(X){var I=new Error(E.source+":"+D+":"+P+": "+X);if(I.reason=X,I.filename=E.source,I.line=D,I.column=P,I.source=A,!E.silent)throw I}function he(X){var I=X.exec(A);if(I){var j=I[0];return J(j),A=A.slice(j.length),I}}function ye(){he(i)}function U(X){var I;for(X=X||[];I=re();)I!==!1&&X.push(I);return X}function re(){var X=q();if(!(d!=A.charAt(0)||_!=A.charAt(1))){for(var I=2;x!=A.charAt(I)&&(_!=A.charAt(I)||d!=A.charAt(I+1));)++I;if(I+=2,x===A.charAt(I-1))return Z("End of comment missing");var j=A.slice(2,I-2);return P+=2,J(j),A=A.slice(I),P+=2,X({type:b,comment:j})}}function W(){var X=q(),I=he(s);if(I){if(re(),!he(a))return Z("property missing ':'");var j=he(o),O=X({type:v,property:N(I[0].replace(e,x)),value:j?N(j[0].replace(e,x)):x});return he(c),O}}function G(){var X=[];U(X);for(var I;I=W();)I!==!1&&(X.push(I),U(X));return X}return ye(),G()}function N(A){return A?A.replace(h,x):x}return ff=y,ff}var cv;function uN(){if(cv)return Qa;cv=1;var e=Qa&&Qa.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.default=i;const t=e(cN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:d,value:_}=p;h?a(d,_,p):_&&(o=o||{},o[d]=_)}),o}return Qa}var co={},uv;function hN(){if(uv)return co;uv=1,Object.defineProperty(co,"__esModule",{value:!0}),co.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(d){return!d||i.test(d)||e.test(d)},c=function(d,_){return _.toUpperCase()},h=function(d,_){return"".concat(_,"-")},p=function(d,_){return _===void 0&&(_={}),o(d)?d:(d=d.toLowerCase(),_.reactCompat?d=d.replace(a,h):d=d.replace(s,h),d.replace(t,c))};return co.camelCase=p,co}var uo,hv;function dN(){if(hv)return uo;hv=1;var e=uo&&uo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(uN()),i=hN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,uo=s,uo}var fN=dN();const pN=Du(fN),w0=C0("end"),Zp=C0("start");function C0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function k0(e){const t=Zp(e),i=w0(e);if(t&&i)return{start:t,end:i}}function vo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?dv(e.position):"start"in e||"end"in e?dv(e):"line"in e||"column"in e?wp(e):""}function wp(e){return fv(e&&e.line)+":"+fv(e&&e.column)}function dv(e){return wp(e&&e.start)+"-"+wp(e&&e.end)}function fv(e){return e&&typeof e=="number"?e:1}class rn extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=vo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}rn.prototype.file="";rn.prototype.name="";rn.prototype.reason="";rn.prototype.message="";rn.prototype.stack="";rn.prototype.column=void 0;rn.prototype.line=void 0;rn.prototype.ancestors=void 0;rn.prototype.cause=void 0;rn.prototype.fatal=void 0;rn.prototype.place=void 0;rn.prototype.ruleId=void 0;rn.prototype.source=void 0;const Qp={}.hasOwnProperty,mN=new Map,gN=/[A-Z]/g,xN=new Set(["table","tbody","thead","tfoot","tr"]),_N=new Set(["td","th"]),E0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function bN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=NN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=EN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Xp:lN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=N0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function N0(e,t,i){if(t.type==="element")return vN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return yN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return wN(e,t,i);if(t.type==="mdxjsEsm")return SN(e,t);if(t.type==="root")return CN(e,t,i);if(t.type==="text")return kN(e,t)}function vN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=j0(e,t.tagName,!1),c=TN(e,t);let h=em(e,t);return xN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!ZE(p):!0})),T0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function yN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Eo(e,t.position)}function SN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Eo(e,t.position)}function wN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:j0(e,t.name,!0),c=jN(e,t),h=em(e,t);return T0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function CN(e,t,i){const s={};return Jp(s,em(e,t)),e.create(t,e.Fragment,s,i)}function kN(e,t){return t.value}function T0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function Jp(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function EN(e,t,i){return s;function s(a,o,c,h){const d=Array.isArray(c.children)?i:t;return h?d(o,c,h):d(o,c)}}function NN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=Zp(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function TN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&Qp.call(t.properties,a)){const o=AN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&_N.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function jN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Eo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Eo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function em(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:mN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?($n(e,e.length,0,t),e):t}const gv={}.hasOwnProperty;function R0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function pr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const dn=Bs(/[A-Za-z]/),nn=Bs(/[\dA-Za-z]/),IN=Bs(/[#-'*+\--9=?A-Z^-~]/);function ju(e){return e!==null&&(e<32||e===127)}const Cp=Bs(/\d/),HN=Bs(/[\dA-Fa-f]/),UN=Bs(/[!-/:-@[-`{-~]/);function $e(e){return e!==null&&e<-2}function Ft(e){return e!==null&&(e<0||e===32)}function xt(e){return e===-2||e===-1||e===32}const Pu=Bs(new RegExp("\\p{P}|\\p{S}","u")),oa=Bs(/\s/);function Bs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function hl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function Ct(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return xt(p)?(e.enter(i),h(p)):t(p)}function h(p){return xt(p)&&o++c))return;const Z=t.events.length;let he=Z,ye,U;for(;he--;)if(t.events[he][0]==="exit"&&t.events[he][1].type==="chunkFlow"){if(ye){U=t.events[he][1].end;break}ye=!0}for(E(s),L=Z;LP;){const q=i[J];t.containerState=q[1],q[0].exit.call(t,e)}i.length=P}function D(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function GN(e,t,i){return Ct(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function al(e){if(e===null||Ft(e)||oa(e))return 1;if(Pu(e))return 2}function Iu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};_v(x,-p),_v(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},d=[],e[s][1].end.offset-e[s][1].start.offset&&(d=rr(d,[["enter",e[s][1],t],["exit",e[s][1],t]])),d=rr(d,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),d=rr(d,Iu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),d=rr(d,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,d=rr(d,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,$n(e,s-1,i-s+3,d),i=s+d.length-_-2;break}}for(i=-1;++i0&&xt(L)?Ct(e,D,"linePrefix",o+1)(L):D(L)}function D(L){return L===null||$e(L)?e.check(bv,N,J)(L):(e.enter("codeFlowValue"),P(L))}function P(L){return L===null||$e(L)?(e.exit("codeFlowValue"),D(L)):(e.consume(L),P)}function J(L){return e.exit("codeFenced"),t(L)}function q(L,Z,he){let ye=0;return U;function U(I){return L.enter("lineEnding"),L.consume(I),L.exit("lineEnding"),re}function re(I){return L.enter("codeFencedFence"),xt(I)?Ct(L,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(L.enter("codeFencedFenceSequence"),G(I)):he(I)}function G(I){return I===h?(ye++,L.consume(I),G):ye>=c?(L.exit("codeFencedFenceSequence"),xt(I)?Ct(L,X,"whitespace")(I):X(I)):he(I)}function X(I){return I===null||$e(I)?(L.exit("codeFencedFence"),Z(I)):he(I)}}}function r5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const mf={name:"codeIndented",tokenize:a5},s5={partial:!0,tokenize:l5};function a5(e,t,i){const s=this;return a;function a(d){return e.enter("codeIndented"),Ct(e,o,"linePrefix",5)(d)}function o(d){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(d):i(d)}function c(d){return d===null?p(d):$e(d)?e.attempt(s5,c,p)(d):(e.enter("codeFlowValue"),h(d))}function h(d){return d===null||$e(d)?(e.exit("codeFlowValue"),c(d)):(e.consume(d),h)}function p(d){return e.exit("codeIndented"),t(d)}}function l5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):$e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):Ct(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):$e(c)?a(c):i(c)}}const o5={name:"codeText",previous:u5,resolve:c5,tokenize:h5};function c5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&ho(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ho(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function z0(e,t,i,s,a,o,c,h,p){const d=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||ju(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),N(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||$e(E)?i(E):(e.consume(E),E===92?y:v)}function y(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||Ft(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):$e(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||$e(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!xt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function I0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),d(b))}function d(b){return b===c?(e.exit(o),p(c)):b===null?i(b):$e(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),Ct(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||$e(b)?(e.exit("chunkString"),d(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function yo(e,t){let i;return s;function s(a){return $e(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?Ct(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const b5={name:"definition",tokenize:y5},v5={partial:!0,tokenize:S5};function y5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return P0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=pr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return Ft(v)?yo(e,d)(v):d(v)}function d(v){return z0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(v5,x,x)(v)}function x(v){return xt(v)?Ct(e,b,"whitespace")(v):b(v)}function b(v){return v===null||$e(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function S5(e,t,i){return s;function s(h){return Ft(h)?yo(e,a)(h):i(h)}function a(h){return I0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?Ct(e,c,"whitespace")(h):c(h)}function c(h){return h===null||$e(h)?t(h):i(h)}}const w5={name:"hardBreakEscape",tokenize:C5};function C5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return $e(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const k5={name:"headingAtx",resolve:E5,tokenize:N5};function E5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},$n(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function N5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||Ft(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||$e(_)?(e.exit("atxHeading"),t(_)):xt(_)?Ct(e,h,"whitespace")(_):(e.enter("atxHeadingText"),d(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function d(_){return _===null||_===35||Ft(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),d)}}const T5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],yv=["pre","script","style","textarea"],j5={concrete:!0,name:"htmlFlow",resolveTo:M5,tokenize:D5},A5={partial:!0,tokenize:L5},R5={partial:!0,tokenize:B5};function M5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function D5(e,t,i){const s=this;let a,o,c,h,p;return d;function d(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,N):C===63?(e.consume(C),a=3,s.interrupt?t:T):dn(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,y):dn(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function y(C){const se="CDATA[";return C===se.charCodeAt(h++)?(e.consume(C),h===se.length?s.interrupt?t:W:y):i(C)}function N(C){return dn(C)?(e.consume(C),c=String.fromCharCode(C),A):i(C)}function A(C){if(C===null||C===47||C===62||Ft(C)){const se=C===47,te=c.toLowerCase();return!se&&!o&&yv.includes(te)?(a=1,s.interrupt?t(C):W(C)):T5.includes(c.toLowerCase())?(a=6,se?(e.consume(C),E):s.interrupt?t(C):W(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?D(C):P(C))}return C===45||nn(C)?(e.consume(C),c+=String.fromCharCode(C),A):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:W):i(C)}function D(C){return xt(C)?(e.consume(C),D):U(C)}function P(C){return C===47?(e.consume(C),U):C===58||C===95||dn(C)?(e.consume(C),J):xt(C)?(e.consume(C),P):U(C)}function J(C){return C===45||C===46||C===58||C===95||nn(C)?(e.consume(C),J):q(C)}function q(C){return C===61?(e.consume(C),L):xt(C)?(e.consume(C),q):P(C)}function L(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,Z):xt(C)?(e.consume(C),L):he(C)}function Z(C){return C===p?(e.consume(C),p=null,ye):C===null||$e(C)?i(C):(e.consume(C),Z)}function he(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Ft(C)?q(C):(e.consume(C),he)}function ye(C){return C===47||C===62||xt(C)?P(C):i(C)}function U(C){return C===62?(e.consume(C),re):i(C)}function re(C){return C===null||$e(C)?W(C):xt(C)?(e.consume(C),re):i(C)}function W(C){return C===45&&a===2?(e.consume(C),j):C===60&&a===1?(e.consume(C),O):C===62&&a===4?(e.consume(C),R):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),xe):$e(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(A5,Y,G)(C)):C===null||$e(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),W)}function G(C){return e.check(R5,X,Y)(C)}function X(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),I}function I(C){return C===null||$e(C)?G(C):(e.enter("htmlFlowData"),W(C))}function j(C){return C===45?(e.consume(C),T):W(C)}function O(C){return C===47?(e.consume(C),c="",B):W(C)}function B(C){if(C===62){const se=c.toLowerCase();return yv.includes(se)?(e.consume(C),R):W(C)}return dn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),B):W(C)}function xe(C){return C===93?(e.consume(C),T):W(C)}function T(C){return C===62?(e.consume(C),R):C===45&&a===2?(e.consume(C),T):W(C)}function R(C){return C===null||$e(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),R)}function Y(C){return e.exit("htmlFlow"),t(C)}}function B5(e,t,i){const s=this;return a;function a(c){return $e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function L5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Lo,t,i)}}const O5={name:"htmlText",tokenize:z5};function z5(e,t,i){const s=this;let a,o,c;return h;function h(T){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(T),p}function p(T){return T===33?(e.consume(T),d):T===47?(e.consume(T),q):T===63?(e.consume(T),P):dn(T)?(e.consume(T),he):i(T)}function d(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,y):dn(T)?(e.consume(T),D):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):$e(T)?(c=x,O(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?j(T):T===45?b(T):x(T)}function y(T){const R="CDATA[";return T===R.charCodeAt(o++)?(e.consume(T),o===R.length?N:y):i(T)}function N(T){return T===null?i(T):T===93?(e.consume(T),A):$e(T)?(c=N,O(T)):(e.consume(T),N)}function A(T){return T===93?(e.consume(T),E):N(T)}function E(T){return T===62?j(T):T===93?(e.consume(T),E):N(T)}function D(T){return T===null||T===62?j(T):$e(T)?(c=D,O(T)):(e.consume(T),D)}function P(T){return T===null?i(T):T===63?(e.consume(T),J):$e(T)?(c=P,O(T)):(e.consume(T),P)}function J(T){return T===62?j(T):P(T)}function q(T){return dn(T)?(e.consume(T),L):i(T)}function L(T){return T===45||nn(T)?(e.consume(T),L):Z(T)}function Z(T){return $e(T)?(c=Z,O(T)):xt(T)?(e.consume(T),Z):j(T)}function he(T){return T===45||nn(T)?(e.consume(T),he):T===47||T===62||Ft(T)?ye(T):i(T)}function ye(T){return T===47?(e.consume(T),j):T===58||T===95||dn(T)?(e.consume(T),U):$e(T)?(c=ye,O(T)):xt(T)?(e.consume(T),ye):j(T)}function U(T){return T===45||T===46||T===58||T===95||nn(T)?(e.consume(T),U):re(T)}function re(T){return T===61?(e.consume(T),W):$e(T)?(c=re,O(T)):xt(T)?(e.consume(T),re):ye(T)}function W(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):$e(T)?(c=W,O(T)):xt(T)?(e.consume(T),W):(e.consume(T),X)}function G(T){return T===a?(e.consume(T),a=void 0,I):T===null?i(T):$e(T)?(c=G,O(T)):(e.consume(T),G)}function X(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||Ft(T)?ye(T):(e.consume(T),X)}function I(T){return T===47||T===62||Ft(T)?ye(T):i(T)}function j(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function O(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),B}function B(T){return xt(T)?Ct(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):xe(T)}function xe(T){return e.enter("htmlTextData"),c(T)}}const nm={name:"labelEnd",resolveAll:U5,resolveTo:$5,tokenize:F5},P5={tokenize:q5},I5={tokenize:W5},H5={tokenize:G5};function U5(e){let t=-1;const i=[];for(;++t=3&&(d===null||$e(d))?(e.exit("thematicBreak"),t(d)):i(d)}function p(d){return d===a?(e.consume(d),s++,p):(e.exit("thematicBreakSequence"),xt(d)?Ct(e,h,"whitespace")(d):h(d))}}const En={continuation:{tokenize:iT},exit:rT,name:"list",tokenize:tT},J5={partial:!0,tokenize:sT},eT={partial:!0,tokenize:nT};function tT(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const y=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Cp(v)){if(s.containerState.type||(s.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(_u,i,d)(v):d(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Cp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),d(v)):i(v)}function d(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Lo,s.interrupt?i:_,e.attempt(J5,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return xt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function iT(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Lo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Ct(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!xt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(eT,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,Ct(e,e.attempt(En,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function nT(e,t,i){const s=this;return Ct(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function rT(e){e.exit(this.containerState.type)}function sT(e,t,i){const s=this;return Ct(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!xt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const Sv={name:"setextUnderline",resolveTo:aT,tokenize:lT};function aT(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function lT(e,t,i){const s=this;let a;return o;function o(d){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=d,c(d)):i(d)}function c(d){return e.enter("setextHeadingLineSequence"),h(d)}function h(d){return d===a?(e.consume(d),h):(e.exit("setextHeadingLineSequence"),xt(d)?Ct(e,p,"lineSuffix")(d):p(d))}function p(d){return d===null||$e(d)?(e.exit("setextHeadingLine"),t(d)):i(d)}}const oT={tokenize:cT};function cT(e){const t=this,i=e.attempt(Lo,s,e.attempt(this.parser.constructs.flowInitial,a,Ct(e,e.attempt(this.parser.constructs.flow,a,e.attempt(p5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const uT={resolveAll:U0()},hT=H0("string"),dT=H0("text");function H0(e){return{resolveAll:U0(e==="text"?fT:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(_){return d(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return d(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function d(_){if(_===null)return!0;const x=a[_];let b=-1;if(x)for(;++b-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function ET(e,t){let i=-1;const s=[];let a;for(;++i0){const H=Pe.tokenStack[Pe.tokenStack.length-1];(H[1]||Cv).call(Pe,void 0,H[0])}for(_e.position={start:Ts(ne.length>0?ne[0][1].start:{line:1,column:1,offset:0}),end:Ts(ne.length>0?ne[ne.length-2][1].end:{line:1,column:1,offset:0})},Qe=-1;++Qe0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function HT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function UT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function $T(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=hl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const d={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,d),e.applyData(t,d)}function FT(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function qT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function q0(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function WT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return q0(e,t);const a={src:hl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function GT(e,t){const i={src:hl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function YT(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function KT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return q0(e,t);const a={href:hl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function VT(e,t){const i={href:hl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function XT(e,t,i){const s=e.all(t),a=i?ZT(i):W0(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h1}function QT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=Zp(t.children[1]),p=w0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function nj(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const d=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Nv(t.slice(a),a>0,!1)),o.join("")}function Nv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===kv||o===Ev;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===kv||o===Ev;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function aj(e,t){const i={type:"text",value:sj(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function lj(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const oj={blockquote:zT,break:PT,code:IT,delete:HT,emphasis:UT,footnoteReference:$T,heading:FT,html:qT,imageReference:WT,image:GT,inlineCode:YT,linkReference:KT,link:VT,listItem:XT,list:QT,paragraph:JT,root:ej,strong:tj,table:ij,tableCell:rj,tableRow:nj,text:aj,thematicBreak:lj,toml:eu,yaml:eu,definition:eu,footnoteDefinition:eu};function eu(){}const G0=-1,Hu=0,So=1,Au=2,rm=3,sm=4,am=5,lm=6,Y0=7,K0=8,Tv=typeof self=="object"?self:globalThis,cj=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Hu:case G0:return i(c,a);case So:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Au:{const h=i({},a);for(const[p,d]of c)h[s(p)]=s(d);return h}case rm:return i(new Date(c),a);case sm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case am:{const h=i(new Map,a);for(const[p,d]of c)h.set(s(p),s(d));return h}case lm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case Y0:{const{name:h,message:p}=c;return i(new Tv[h](p),a)}case K0:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Tv[o](c),a)};return s},jv=e=>cj(new Map,e)(0),Ja="",{toString:uj}={},{keys:hj}=Object,fo=e=>{const t=typeof e;if(t!=="object"||!e)return[Hu,t];const i=uj.call(e).slice(8,-1);switch(i){case"Array":return[So,Ja];case"Object":return[Au,Ja];case"Date":return[rm,Ja];case"RegExp":return[sm,Ja];case"Map":return[am,Ja];case"Set":return[lm,Ja];case"DataView":return[So,i]}return i.includes("Array")?[So,i]:i.includes("Error")?[Y0,i]:[Au,i]},tu=([e,t])=>e===Hu&&(t==="function"||t==="symbol"),dj=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=fo(c);switch(h){case Hu:{let _=c;switch(p){case"bigint":h=K0,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([G0],c)}return a([h,_],c)}case So:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Au:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of hj(c))(e||!tu(fo(c[b])))&&_.push([o(b),o(c[b])]);return x}case rm:return a([h,c.toISOString()],c);case sm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case am:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(tu(fo(b))||tu(fo(v))))&&_.push([o(b),o(v)]);return x}case lm:{const _=[],x=a([h,_],c);for(const b of c)(e||!tu(fo(b)))&&_.push(o(b));return x}}const{message:d}=c;return a([h,{name:p,message:d}],c)};return o},Av=(e,{json:t,lossy:i}={})=>{const s=[];return dj(!(t||i),!!t,new Map,s)(e),s},No=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?jv(Av(e,t)):structuredClone(e):(e,t)=>jv(Av(e,t));function fj(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function pj(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function mj(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||fj,s=e.options.footnoteBackLabel||pj,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&y.push({type:"text",value:" "});let D=typeof i=="string"?i:i(p,v);typeof D=="string"&&(D={type:"text",value:D}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(D)?D:[D]})}const A=_[_.length-1];if(A&&A.type==="element"&&A.tagName==="p"){const D=A.children[A.children.length-1];D&&D.type==="text"?D.value+=" ":A.children.push({type:"text",value:" "}),A.children.push(...y)}else _.push(...y);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(d,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...No(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` -`}]}}const Uu=(function(e){if(e==null)return bj;if(typeof e=="function")return $u(e);if(typeof e=="object")return Array.isArray(e)?gj(e):xj(e);if(typeof e=="string")return _j(e);throw new Error("Expected function, string, or object as test")});function gj(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=V0,y,N,A;if((!t||o(p,d,_[_.length-1]||void 0))&&(v=wj(i(p,_)),v[0]===Ep))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==Sj)for(N=(s?E.children.length:-1)+c,A=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` -`}),i}function Rv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Mv(e,t){const i=kj(e,t),s=i.one(e,void 0),a=mj(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function Aj(e,t){return e&&"run"in e?async function(i,s){const a=Mv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Mv(i,{file:s,...e||t})}}function Dv(e){if(e)throw e}var xf,Bv;function Rj(){if(Bv)return xf;Bv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(d){return typeof Array.isArray=="function"?Array.isArray(d):t.call(d)==="[object Array]"},o=function(d){if(!d||t.call(d)!=="[object Object]")return!1;var _=e.call(d,"constructor"),x=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!_&&!x)return!1;var b;for(b in d);return typeof b>"u"||e.call(d,b)},c=function(d,_){i&&_.name==="__proto__"?i(d,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):d[_.name]=_.newValue},h=function(d,_){if(_==="__proto__")if(e.call(d,_)){if(s)return s(d,_).value}else return;return d[_]};return xf=function p(){var d,_,x,b,v,y,N=arguments[0],A=1,E=arguments.length,D=!1;for(typeof N=="boolean"&&(D=N,N=arguments[1]||{},A=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Ac.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(d){const _=d;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const wr={basename:Lj,dirname:Oj,extname:zj,join:Pj,sep:"/"};function Lj(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Oo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function Oj(e){if(Oo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function zj(e){Oo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function Pj(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function Hj(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Oo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Uj={cwd:$j};function $j(){return"/"}function jp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Fj(e){if(typeof e=="string")e=new URL(e);else if(!jp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return qj(e)}function qj(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...y]=_;const N=s[b][1];Tp(N)&&Tp(v)&&(v=_f(!0,N,v)),s[b]=[d,v,...y]}}}}const Kj=new cm().freeze();function Sf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Cf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ov(e){if(!Tp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function zv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function iu(e){return Vj(e)?e:new Z0(e)}function Vj(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Xj(e){return typeof e=="string"||Zj(e)}function Zj(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Qj="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Pv=[],Iv={allowDangerousHtml:!0},Jj=/^(https?|ircs?|mailto|xmpp)$/i,eA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Q0(e){const t=tA(e),i=iA(e);return nA(t.runSync(t.parse(i),i),e)}function tA(e){const t=e.rehypePlugins||Pv,i=e.remarkPlugins||Pv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Iv}:Iv;return Kj().use(OT).use(i).use(Aj,s).use(t)}function iA(e){const t=e.children||"",i=new Z0;return typeof t=="string"&&(i.value=t),i}function nA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||rA;for(const _ of eA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+Qj+_.id,void 0);return om(e,d),bN(e,{Fragment:f.Fragment,components:a,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function d(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in pf)if(Object.hasOwn(pf,v)&&Object.hasOwn(_.properties,v)){const y=_.properties[v],N=pf[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(y||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function rA(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||Jj.test(e.slice(0,t))?e:""}function sA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function J0(e,t,i){const a=Uu((i||{}).ignore||[]),o=aA(t);let c=-1;for(;++c0?{type:"text",value:L}:void 0),L===!1?b.lastIndex=J+1:(y!==J&&D.push({type:"text",value:d.value.slice(y,J)}),Array.isArray(L)?D.push(...L):L&&D.push(L),y=J+P[0].length,E=!0),!b.global)break;P=b.exec(d.value)}return E?(y?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Hv(e,"(");let o=Hv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function tS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||oa(i)||Pu(i))&&(!t||i!==47)}iS.peek=RA;function wA(){this.buffer()}function CA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function kA(){this.buffer()}function EA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function NA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=pr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function TA(e){this.exit(e)}function jA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=pr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function AA(e){this.exit(e)}function RA(){return"["}function iS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function MA(){return{enter:{gfmFootnoteCallString:wA,gfmFootnoteCall:CA,gfmFootnoteDefinitionLabelString:kA,gfmFootnoteDefinition:EA},exit:{gfmFootnoteCallString:NA,gfmFootnoteCall:TA,gfmFootnoteDefinitionLabelString:jA,gfmFootnoteDefinition:AA}}}function DA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:iS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const d=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` -`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?nS:BA))),d(),p}}function BA(e,t,i){return t===0?e:nS(e,t,i)}function nS(e,t,i){return(i?"":" ")+e}const LA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];rS.peek=HA;function OA(){return{canContainEols:["delete"],enter:{strikethrough:PA},exit:{strikethrough:IA}}}function zA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:LA}],handlers:{delete:rS}}}function PA(e){this.enter({type:"delete",children:[]},e)}function IA(e){this.exit(e)}function rS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function HA(){return"~"}function UA(e){return e.length}function $A(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||UA,o=[],c=[],h=[],p=[];let d=0,_=-1;for(;++_d&&(d=e[_].length);++Ep[E])&&(p[E]=P)}N.push(D)}c[_]=N,h[_]=A}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=D),v[x]=D),b[x]=P}c.splice(1,0,b),h.splice(1,0,v),_=-1;const y=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),WA);return a(),c}function WA(e,t,i){return">"+(i?"":" ")+e}function GA(e,t){return $v(e,t.inConstruct,!0)&&!$v(e,t.notInConstruct,!1)}function $v(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function KA(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function VA(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function XA(e,t,i,s){const a=VA(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(KA(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,ZA);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(YA(o,a)+1,3)),d=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` -`,encode:["`"],...h.current()})),x()}return _+=h.move(` -`),o&&(_+=h.move(o+` -`)),_+=h.move(p),d(),_}function ZA(e,t,i){return(i?"":" ")+e}function um(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function QA(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("[");return d+=p.move(i.safe(i.associationId(e),{before:d,after:"]",...p.current()})),d+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),c(),d}function JA(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function To(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ru(e,t,i){const s=al(e),a=al(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}sS.peek=eR;function sS(e,t,i,s){const a=JA(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),_=Ru(s.before.charCodeAt(s.before.length-1),d,a);_.inside&&(p=To(d)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function eR(e,t,i){return i.options.emphasis||"*"}function tR(e,t){let i=!1;return om(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ep}),!!((!e.depth||e.depth<3)&&tm(e)&&(t.options.setext||i))}function iR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(tR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` -`,after:` -`});return x(),_(),b+` -`+(a===1?"=":"-").repeat(b.length-(Math.max(b.lastIndexOf("\r"),b.lastIndexOf(` -`))+1))}const c="#".repeat(a),h=i.enter("headingAtx"),p=i.enter("phrasing");o.move(c+" ");let d=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(d)&&(d=To(d.charCodeAt(0))+d.slice(1)),d=d?c+" "+d:c,i.options.closeAtx&&(d+=" "+c),p(),h(),d}aS.peek=nR;function aS(e){return e.value||""}function nR(){return"<"}lS.peek=rR;function lS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let d=p.move("![");return d+=p.move(i.safe(e.alt,{before:d,after:"]",...p.current()})),d+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),d+=p.move("<"),d+=p.move(i.safe(e.url,{before:d,after:">",...p.current()})),d+=p.move(">")):(h=i.enter("destinationRaw"),d+=p.move(i.safe(e.url,{before:d,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),d+=p.move(" "+a),d+=p.move(i.safe(e.title,{before:d,after:a,...p.current()})),d+=p.move(a),h()),d+=p.move(")"),c(),d}function rR(){return"!"}oS.peek=sR;function oS(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const d=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!d||d!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function sR(){return"!"}cS.peek=aR;function cS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}hS.peek=lR;function hS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(uS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let d=c.move("[");return d+=c.move(i.containerPhrasing(e,{before:d,after:"](",...c.current()})),d+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),d+=c.move("<"),d+=c.move(i.safe(e.url,{before:d,after:">",...c.current()})),d+=c.move(">")):(p=i.enter("destinationRaw"),d+=c.move(i.safe(e.url,{before:d,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),d+=c.move(" "+a),d+=c.move(i.safe(e.title,{before:d,after:a,...c.current()})),d+=c.move(a),p()),d+=c.move(")"),h(),d}function lR(e,t,i){return uS(e,i)?"<":"["}dS.peek=oR;function dS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const d=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(d+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!d||d!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function oR(){return"["}function hm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function cR(e){const t=hm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function uR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function fS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function hR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?uR(i):hm(i);const h=e.ordered?c==="."?")":".":cR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),fS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),d=i.indentLines(i.containerFlow(e,h.current()),_);return p(),d;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function pR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const mR=Uu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function gR(e,t,i,s){return(e.children.some(function(c){return mR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function xR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}pS.peek=_R;function pS(e,t,i,s){const a=xR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const d=p.charCodeAt(0),_=Ru(s.before.charCodeAt(s.before.length-1),d,a);_.inside&&(p=To(d)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function _R(e,t,i){return i.options.strong||"*"}function bR(e,t,i,s){return i.safe(e.value,s)}function vR(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function yR(e,t,i){const s=(fS(i)+(i.options.ruleSpaces?" ":"")).repeat(vR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const mS={blockquote:qA,break:Fv,code:XA,definition:QA,emphasis:sS,hardBreak:Fv,heading:iR,html:aS,image:lS,imageReference:oS,inlineCode:cS,link:hS,linkReference:dS,list:hR,listItem:fR,paragraph:pR,root:gR,strong:pS,text:bR,thematicBreak:yR};function SR(){return{enter:{table:wR,tableData:qv,tableHeader:qv,tableRow:kR},exit:{codeText:ER,table:CR,tableData:Tf,tableHeader:Tf,tableRow:Tf}}}function wR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function CR(e){this.exit(e),this.data.inTable=void 0}function kR(e){this.enter({type:"tableRow",children:[]},e)}function Tf(e){this.exit(e)}function qv(e){this.enter({type:"tableCell",children:[]},e)}function ER(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,NR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function NR(e,t){return t==="|"?t:e}function TR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,y,N,A){return d(_(v,N,A),v.align)}function h(v,y,N,A){const E=x(v,N,A),D=d([E]);return D.slice(0,D.indexOf(` -`))}function p(v,y,N,A){const E=N.enter("tableCell"),D=N.enter("phrasing"),P=N.containerPhrasing(v,{...A,before:o,after:o});return D(),E(),P}function d(v,y){return $A(v,{align:y,alignDelimiters:s,padding:i,stringLength:a})}function _(v,y,N){const A=v.children;let E=-1;const D=[],P=y.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const GR={tokenize:e3,partial:!0};function YR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ZR,continuation:{tokenize:QR},exit:JR}},text:{91:{name:"gfmFootnoteCall",tokenize:XR},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:KR,resolveTo:VR}}}}function KR(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const d=pr(s.sliceSerialize({start:c.end,end:s.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function VR(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function XR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(x){if(o>999||x===93&&!c||x===null||x===91||Ft(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(pr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Ft(x)||(c=!0),o++,e.consume(x),x===92?_:d}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,d):d(x)}}function ZR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(y)}function _(y){if(c>999||y===93&&!h||y===null||y===91||Ft(y))return i(y);if(y===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=pr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Ft(y)||(h=!0),c++,e.consume(y),y===92?x:_}function x(y){return y===91||y===92||y===93?(e.consume(y),c++,_):_(y)}function b(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),a.includes(o)||a.push(o),Ct(e,v,"gfmFootnoteDefinitionWhitespace")):i(y)}function v(y){return t(y)}}function QR(e,t,i){return e.check(Lo,t,e.attempt(GR,t,i))}function JR(e){e.exit("gfmFootnoteDefinition")}function e3(e,t,i){const s=this;return Ct(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function t3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(y):(c.consume(y),x++,v);if(x<2&&!i)return p(y);const A=c.exit("strikethroughSequenceTemporary"),E=al(y);return A._open=!E||E===2&&!!N,A._close=!N||N===2&&!!E,h(y)}}}class i3{constructor(){this.map=[]}add(t,i,s){n3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function n3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const X=s.events[re][1].type;if(X==="lineEnding"||X==="linePrefix")re--;else break}const W=re>-1?s.events[re][1].type:null,G=W==="tableHead"||W==="tableRow"?L:p;return G===L&&s.parser.lazy[s.now().line]?i(U):G(U)}function p(U){return e.enter("tableHead"),e.enter("tableRow"),d(U)}function d(U){return U===124||(c=!0,o+=1),_(U)}function _(U){return U===null?i(U):$e(U)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(U),e.exit("lineEnding"),v):i(U):xt(U)?Ct(e,_,"whitespace")(U):(o+=1,c&&(c=!1,a+=1),U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(U)))}function x(U){return U===null||U===124||Ft(U)?(e.exit("data"),_(U)):(e.consume(U),U===92?b:x)}function b(U){return U===92||U===124?(e.consume(U),x):x(U)}function v(U){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(U):(e.enter("tableDelimiterRow"),c=!1,xt(U)?Ct(e,y,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):y(U))}function y(U){return U===45||U===58?A(U):U===124?(c=!0,e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),N):q(U)}function N(U){return xt(U)?Ct(e,A,"whitespace")(U):A(U)}function A(U){return U===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),E):U===45?(o+=1,E(U)):U===null||$e(U)?J(U):q(U)}function E(U){return U===45?(e.enter("tableDelimiterFiller"),D(U)):q(U)}function D(U){return U===45?(e.consume(U),D):U===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(U),e.exit("tableDelimiterMarker"),P):(e.exit("tableDelimiterFiller"),P(U))}function P(U){return xt(U)?Ct(e,J,"whitespace")(U):J(U)}function J(U){return U===124?y(U):U===null||$e(U)?!c||a!==o?q(U):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(U)):q(U)}function q(U){return i(U)}function L(U){return e.enter("tableRow"),Z(U)}function Z(U){return U===124?(e.enter("tableCellDivider"),e.consume(U),e.exit("tableCellDivider"),Z):U===null||$e(U)?(e.exit("tableRow"),t(U)):xt(U)?Ct(e,Z,"whitespace")(U):(e.enter("data"),he(U))}function he(U){return U===null||U===124||Ft(U)?(e.exit("data"),Z(U)):(e.consume(U),U===92?ye:he)}function ye(U){return U===92||U===124?(e.consume(U),he):he(U)}}function l3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,d,_,x;const b=new i3;for(;++ii[2]+1){const y=i[2]+1,N=i[3]-i[2]-1;e.add(y,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},el(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Gv(e,t,i,s,a){const o=[],c=el(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function el(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const o3={name:"tasklistCheck",tokenize:u3};function c3(){return{text:{91:o3}}}function u3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return Ft(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return $e(p)?t(p):xt(p)?e.check({tokenize:h3},t,i)(p):i(p)}}function h3(e,t,i){return Ct(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function d3(e){return R0([zR(),YR(),t3(e),s3(),c3()])}const f3={};function CS(e){const t=this,i=e||f3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(d3(i)),o.push(DR()),c.push(BR(i))}const ta=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ll={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ta,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ta],h2:[["className","sr-only"]],img:[...ta,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ta,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ta],table:[...ta],ul:[...ta,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},As={}.hasOwnProperty;function p3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ll,...t}:ll,stack:[]},a=kS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function kS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return m3(e,i);case"doctype":return g3(e,i);case"element":return x3(e,i);case"root":return _3(e,i);case"text":return b3(e,i)}}}function m3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return zo(o,t),o}}function g3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return zo(i,t),i}}function x3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=ES(e,t.children),a=v3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&As.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let d=-1;for(;++d4&&t.slice(0,4).toLowerCase()==="data")return i}function TS(e){return function(t){return p3(t,e)}}const nl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],Xr=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function jS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const w3=Object.fromEntries(nl.map(e=>[jS(e),e])),C3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function bu(e){if(!e)return null;const t=jS(e.trim());return t?w3[t]??C3[t]??null:null}function AS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function RS(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(AS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function Rp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=RS(e,t,i);return h||!c&&!o?f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:f.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?f.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):f.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:f.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function Vv(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function ru(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),d=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=N=>{const A=a.hasSpeaker?N*c:0,E=a.hasSpeaker?A*o:0,D=Math.max(1,_-E),P=a.fontWeight??400,J=Vv((Z,he)=>e(Z,he,P),t,d,N),q=J.length*N*o,L=J.every(Z=>e(Z,N,P)<=d+.5);return{lines:J,ok:q<=D&&L}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:A,ok:E}=v(N);return{lines:A,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:A,ok:E}=v(N);if(E)return{lines:A,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:Vv(e,t,d,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function k3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const MS=["speech","narration","sfx"],E3=2;function kr(e,t,i){return Math.min(i,Math.max(t,e))}function rl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?kr(e,t,i):void 0}function fm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=rl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=rl(t.lineHeightFactor,.9,2),c=rl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Fu(e){if(!e||typeof e!="object")return;const t=e,i=rl(t.paddingX,0,.25),s=rl(t.paddingY,0,.25),a=rl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function su(e,t,i,s){const{minFontSize:a,maxFontSize:o}=k3(t),c=fm(e.textStyle),h=Fu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function N3(e,t,i){const s=Fu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function DS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Xv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?kr(e,h,p):t+i/2,half:c}}function BS(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,d=t+a.y*s;if(p>=e&&p<=e+i&&d>=t&&d<=t+s)return null;const _=p-c,x=d-h,b=Math.max(6,Math.min(i,s)*.3),v=o??DS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:D,half:P}=Xv(p,e,i,v,b);return{tip:{x:p,y:d},base1:{x:D-P,y:E},base2:{x:D+P,y:E}}}const y=_>=0?e+i:e,{center:N,half:A}=Xv(d,t,s,v,b);return{tip:{x:p,y:d},base1:{x:y,y:N-A},base2:{x:y,y:N+A}}}function T3(e){return e.type!=="speech"||!e.tailAnchor?!1:BS(0,0,1,1,e.tailAnchor)!==null}function j3(e,t,i,s,a,o){const c=o??DS(i,s),h=e+i,p=t+s,d=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return d&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function A3(e,t,i,s,a,o){const c=j3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function R3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let Zv=0;function Qv(e,t=.1,i=.1){return Zv++,{id:`overlay-${Date.now()}-${Zv}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function M3(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const au=.05;function Hi(e){return typeof e=="number"&&Number.isFinite(e)}function D3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const d=a?au:kr(o?1-t-au:(1-t)/2,0,1),_=c?au:kr(h?1-i-au:(1-i)/2,0,1);return{x:d,y:_}}let B3=0;function L3(e){if(!e||typeof e!="object")return null;const t=e,i=MS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Hi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Hi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Hi(t.x)&&Hi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?D3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=kr(c,0,1),h=kr(h,0,1),a=kr(a,.02,1),o=kr(o,.02,1);const d={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++B3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){d.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;d.tailAnchor=b&&Hi(b.x)&&Hi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(d.speaker=t.speaker);const _=fm(t.textStyle),x=Fu(t.bubbleStyle);return _&&(d.textStyle=_),x&&(d.bubbleStyle=x),d}function O3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&MS.includes(t.type)&&Hi(t.x)&&Hi(t.y)&&Hi(t.width)&&Hi(t.height)&&typeof t.text=="string"}function z3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=L3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),O3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function VD(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=fm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Fu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const Jv=new Set(["speech","narration"]),P3=.12;function ey(e){return Hi(e==null?void 0:e.x)&&Hi(e==null?void 0:e.y)&&Hi(e==null?void 0:e.width)&&Hi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function I3(e,t=P3){const i=[];for(let s=0;s0?d/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function Er(e){return e.kind==="text"}function H3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||Er(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function LS(e,t=E3){return!e.finalImagePath||!(e.overlays??[]).some(T3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ty,height:Math.round(ty*s/i)}}function lu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?f.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>f.jsxs("div",{className:"flex gap-2 text-xs",children:[f.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),f.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&f.jsx("div",{className:"border-l-2 border-border pl-3",children:f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&f.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function $3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),f.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&f.jsx(Rp,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&f.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[f.jsx(Rp,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),f.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:f.jsx(lu,{cut:e})})]}),!c&&p&&f.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?f.jsx(lu,{cut:e}):f.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&f.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[f.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[f.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),f.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&f.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[f.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),f.jsx(lu,{cut:e})]})]}),e.description&&f.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&f.jsx(lu,{cut:e}),s&&(()=>{const d=H3(e);return f.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":d.key,onClick:()=>s(e.id,d.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:d.label})})()]})}function F3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,d]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),d(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const y=await b.json();d(y.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{d("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:p}),f.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),f.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):f.jsx("div",{className:"h-full overflow-y-auto",children:f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>f.jsx($3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const iy=/!\[[^\]]*\]\([^)]*\)/g,q3=//g,OS=200;function W3(e){const t=(e.match(iy)||[]).length,i=e.length,s=e.replace(q3," ").replace(iy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,OS)}}function G3(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const Y3=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function K3(e){for(const t of Y3){const i=e.match(t);if(i)return i[0]}return null}function pm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=K3(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function PS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(V3(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=zS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const jf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function X3(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,d)=>p-d);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function IS(e){const t=c=>{var h;return((h=jf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...jf.map(c=>c.key),"other"],a=c=>{var h;return((h=jf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:X3(h)})}return o}const Z3=220,Af=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function mm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Af.test(x)).length,d=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=d.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Af.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):d.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Af.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function Q3(e){return/\.(webp|jpe?g)$/i.test(e)}function Mp(e){var c;let t=0,i=0,s=0,a=0,o=0;for(const h of e)Er(h)||(t++,h.cleanImagePath&&Q3(h.cleanImagePath)&&(i++,(((c=h.overlays)==null?void 0:c.length)??0)>0&&s++)),h.finalImagePath&&h.exportedAt&&a++,h.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const J3={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function ou(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function eM(e){const{cuts:t,published:i=!1}=e,s=Mp(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.needClean,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(D=>!_[D]),v=D=>s.needClean>0?ou(D,s.needClean):"no image cuts",y={plan:ou(s.total,s.total),clean:v(s.withClean),letter:v(s.withText),export:ou(s.exported,s.total),upload:ou(s.uploaded,s.total),publish:null},N=x.map((D,P)=>({key:D,label:J3[D],status:b===-1||POS,a=nM({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[f.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[f.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),f.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),f.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),f.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${sM[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[f.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&f.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&f.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&f.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[f.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),f.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),f.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),f.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Q0,{remarkPlugins:[eS,CS],rehypePlugins:[[TS,rM]],children:e})}):f.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const lM="modulepreload",oM=function(e){return"/"+e},ny={},ry=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(d){return Promise.all(d.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(d=>{if(d=oM(d),d in ny)return;ny[d]=!0;const _=d.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":lM,_||(b.as="script"),b.crossOrigin="",b.href=d,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,y)=>{b.addEventListener("load",v),b.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},gm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],cM="system-ui, sans-serif",uM=gm.find(e=>e.family==="Noto Sans"),hM=gm.find(e=>e.category==="display");function dM(e){return gm.find(i=>i.category==="body"&&i.languages.includes(e))||uM}function fM(){return hM}function pM(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function sy(e){return`"${e.family}", ${cM}`}function mM(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function vu(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function gM(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==vu(e.current)}function HS(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function kn(e,t){return e*t}function ay(e,t){return t===0?0:e/t}function ly(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=pM(e),document.head.appendChild(i)}const yu={speech:"Speech",narration:"Narration",sfx:"SFX"},xM={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Rf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:yu[e.type]}const oy=.05,_M=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function cu(e,t,i){return Math.min(i,Math.max(t,e))}function bM({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h}){var fi,ne,_e,Pe,Fe,Qe;const p=dM(c),d=fM(),_=sy(p),x=sy(d);w.useEffect(()=>{ly(p),ly(d)},[p,d]),w.useEffect(()=>{let H=!1;return ye(!1),(async()=>{try{const{ensureFontsReady:ge}=await ry(async()=>{const{ensureFontsReady:Te}=await import("./export-cut-DAQ_YjPc.js");return{ensureFontsReady:Te}},[]);await ge([p.family,d.family])}catch{}H||ye(!0)})(),()=>{H=!0}},[p.family,d.family]);const b=RS(e,t.cleanImagePath,h),v=w.useMemo(()=>z3(t.overlays),[t.overlays]),y=v.invalid.length,[N,A]=w.useState(!1),E=y===0&&v.changed&&v.overlays.length>0,[D,P]=w.useState(()=>v.overlays),[J,q]=w.useState(()=>vu(v.overlays)),L=w.useRef(null),Z=w.useCallback(H=>(ge,Te,me=400)=>{var Le;!L.current&&typeof document<"u"&&(L.current=document.createElement("canvas"));const He=(Le=L.current)==null?void 0:Le.getContext("2d");return He?(He.font=`${me} ${Te}px ${H}`,He.measureText(ge).width):ge.length*Te*.5},[]),[he,ye]=w.useState(!1),[U,re]=w.useState(null),[W,G]=w.useState(!1),[X,I]=w.useState(!1),[j,O]=w.useState(null),[B,xe]=w.useState({x:0,y:0,width:0,height:0}),T=w.useRef(null),R=w.useRef(null),Y=w.useRef(null),C=w.useCallback(()=>{const H=T.current;if(!H)return;const ge=H.clientWidth,Te=H.clientHeight;let me,He;if(t.kind==="text"){const Mt=U3(t.aspectRatio)??{width:800,height:600};me=Mt.width,He=Mt.height}else{const Mt=R.current;if(!Mt||!Mt.naturalWidth)return;me=Mt.naturalWidth,He=Mt.naturalHeight}if(!ge||!Te)return;const Le=Math.min(ge/me,Te/He),ht=me*Le,it=He*Le;xe({x:(ge-ht)/2,y:(Te-it)/2,width:ht,height:it})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=T.current;if(!H)return;const ge=new ResizeObserver(()=>C());return ge.observe(H),()=>ge.disconnect()},[C]);const se=w.useCallback(H=>{const ge=M3(H.type,H.x,H.y),Te=ge.width,me=Math.max(.08,1-H.y);if(!H.text||!he||B.width<=0)return ge;const He=H.type==="sfx"?x:_,Le=kn(Te,B.width);let ht=H.type==="sfx"?.08:.12;for(let it=0;it<24;it++){const Mt=Math.min(ht,me),Dt=kn(Mt,B.height);if(!ru(Z(He),H.text,Le,Dt,su({...H},B.height||300,Le,Dt)).overflow||Mt>=me)return{width:Te,height:Mt};ht+=.03}return{width:Te,height:Math.min(ht,me)}},[he,B,Z,_,x]),te=w.useCallback(H=>{const ge=Qv(H,.1+Math.random()*.3,.1+Math.random()*.3),Te={...ge,...se(ge)};P(me=>[...me,Te]),re(Te.id)},[se]),oe=w.useCallback(H=>{const Te={...Qv(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},me={...Te,...se(Te)};P(He=>[...He,me]),re(me.id)},[se]),$=w.useCallback((H,ge)=>{P(Te=>Te.map(me=>me.id===H?{...me,...ge}:me))},[]),ue=w.useCallback(H=>{var ht;const ge=B.height||300,Te=B.width>0?kn(H.width,B.width):200,me=B.height>0?kn(H.height,B.height):100,He=H.type==="sfx"?x:_,Le=ru(Z(He),H.text,Te,me,su({...H,textStyle:void 0},ge,Te,me));$(H.id,{textStyle:{mode:"manual",fontScale:Le.fontSize/Math.max(1,ge),fontWeight:((ht=H.textStyle)==null?void 0:ht.fontWeight)??400,lineHeightFactor:Le.fontSize>0?Le.lineHeight/Le.fontSize:1.2,speakerScale:Le.fontSize>0&&Le.speakerFontSize>0?Le.speakerFontSize/Le.fontSize:.8}})},[B,x,_,Z,$]),be=w.useCallback(H=>{P(ge=>ge.filter(Te=>Te.id!==H)),re(null),G(!1)},[]),De=w.useCallback(()=>{re(null),G(!1)},[]),Ee=w.useCallback((H,ge)=>{H.stopPropagation(),re(ge),G(!1)},[]),Be=w.useCallback((H,ge,Te)=>{H.stopPropagation(),H.preventDefault();const me=D.find(He=>He.id===ge);me&&(re(ge),Y.current={id:ge,mode:Te,startX:H.clientX,startY:H.clientY,origX:me.x,origY:me.y,origW:me.width,origH:me.height})},[D]);w.useEffect(()=>{const H=Te=>{const me=Y.current;if(!me||B.width===0)return;const He=ay(Te.clientX-me.startX,B.width),Le=ay(Te.clientY-me.startY,B.height);if(me.mode==="move"){const ht=cu(me.origX+He,0,1-me.origW),it=cu(me.origY+Le,0,1-me.origH);$(me.id,{x:ht,y:it})}else{const ht=cu(me.origW+He,oy,1-me.origX),it=cu(me.origH+Le,oy,1-me.origY);$(me.id,{width:ht,height:it})}},ge=()=>{Y.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",ge),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",ge)}},[B,$]);const je=w.useCallback(()=>{s(D)},[D,s]),Ze=w.useCallback(async()=>{if(y>0&&!N){const H=y;O(`${H} overlay${H===1?"":"s"} from the cut plan ${H===1?"has":"have"} no usable position and cannot be exported — re-place ${H===1?"it":"them"} or discard ${H===1?"it":"them"} first.`);return}I(!0),O(null);try{await s(D);const{exportCut:H,ensureFontsReady:ge}=await ry(async()=>{const{exportCut:kt,ensureFontsReady:ki}=await import("./export-cut-DAQ_YjPc.js");return{exportCut:kt,ensureFontsReady:ki}},[]),Te=D.some(kt=>kt.type==="sfx"),me=[p.family,...Te?[d.family]:[]],{ready:He,missing:Le}=await ge(me);if(!He){O(`Fonts not loaded: ${Le.join(", ")}. Check your connection and retry.`),I(!1);return}if(t.cleanImagePath&&!b.url){O(b.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),I(!1);return}const ht=b.url,it=await H(ht,D,_,x,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),Mt=new FormData,Dt=it.type==="image/webp"?"webp":"jpg";Mt.append("file",it,`cut-${t.id}.${Dt}`);const pi=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:Mt});if(pi.ok)q(vu(D)),o==null||o();else{const kt=await pi.json();O(kt.error||"Export failed")}}catch(H){O(H instanceof Error?H.message:"Export failed")}finally{I(!1)}},[t,b,D,e,i,p,d,_,x,h,s,o,y,N]),Ce=D.find(H=>H.id===U),tt=w.useMemo(()=>I3(D),[D]),pt=w.useRef(t.id);w.useEffect(()=>{pt.current!==t.id&&(pt.current=t.id,q(vu(v.overlays)))},[t.id,v.overlays]);const Ge=gM({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:J,current:D}),Ae=w.useMemo(()=>mM({...t,overlays:D},{staleExport:Ge}),[t,D,Ge]),Ve=w.useMemo(()=>HS(t),[t]),At=w.useMemo(()=>{const H={};for(const ge of D){const Te=R3(ge);let me=!1;if(he&&B.width>0&&ge.text){const He=ge.type==="sfx"?x:_,Le=kn(ge.width,B.width),ht=kn(ge.height,B.height);me=ru(Z(He),ge.text,Le,ht,su(ge,B.height||300,Le,ht)).overflow}(Te||me)&&(H[ge.id]={outOfBounds:Te,overflow:me})}return H},[D,he,B,Z,_,x]),Ot=Object.keys(At).length,ci=t.kind==="text",St=!t.cleanImagePath;return!ci&&St&&D.length===0&&!t.narration&&!((fi=t.dialogue)!=null&&fi.length)?f.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-xs font-mono text-muted",children:["Cut #",t.id]}),f.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[D.length," overlays"]}),f.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[f.jsx("button",{onClick:()=>te("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),f.jsx("button",{onClick:()=>te("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),f.jsx("button",{onClick:()=>te("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[j&&f.jsx("span",{className:"text-[10px] text-error",children:j}),f.jsx("button",{onClick:Ze,disabled:X,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:X?"Exporting...":"Export"}),f.jsx("button",{onClick:je,className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim",children:"Save"}),f.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded",children:"Close"})]})]}),y>0&&!N?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[f.jsxs("span",{children:[y," overlay",y===1?"":"s"," from the cut plan ",y===1?"has":"have"," no usable position and cannot be exported. Re-place ",y===1?"it":"them",", or"]}),f.jsxs("button",{onClick:()=>A(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",y," unplaceable overlay",y===1?"":"s"]})]}):y>0?f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",y," unplaceable overlay",y===1?"":"s"," — the export will not include ",y===1?"it":"them","."]}):E?f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,tt.length>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",tt.length," bubble ",tt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",tt.map(H=>`#${H.indexA+1} ${Rf(D[H.indexA])} ↔ #${H.indexB+1} ${Rf(D[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),f.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",Ae.hasCleanImage],["script-text","Script text",Ae.hasScriptText],["bubbles",`Bubbles placed${Ae.bubblesPlaced?` (${Ae.bubblesPlaced})`:""}`,Ae.bubblesPlaced>0],["exported","Final exported",Ae.exported],["uploaded","Uploaded",Ae.uploaded]].map(([H,ge,Te])=>f.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Te?"true":"false",className:`flex items-center gap-1 ${Te?"text-green-700":"text-muted/70"}`,children:[f.jsx("span",{"aria-hidden":!0,children:Te?"✓":"○"}),ge]},H))}),Ge&&f.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Ot>0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[Ot," bubble",Ot===1?"":"s"," may not export cleanly:"," ",Object.entries(At).map(([H,ge])=>{const Te=D.findIndex(He=>He.id===H),me=[ge.outOfBounds?"outside image":null,ge.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Te+1} ${Rf(D[Te])} (${me})`}).join("; "),". Resize or reposition before exporting."]}),f.jsxs("div",{className:"flex-1 min-h-0 flex",children:[f.jsxs("div",{ref:T,className:"flex-1 min-w-0 relative overflow-hidden",onClick:De,"data-testid":"editor-surface",children:[t.cleanImagePath&&b.error?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!b.url?f.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?f.jsx("img",{ref:R,src:b.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:C}):ci?B.width>0&&f.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:B.x,top:B.y,width:B.width,height:B.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):f.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&B.width===0){const ge=H.getBoundingClientRect();ge.width>0&&xe({x:0,y:0,width:ge.width,height:ge.height})}},children:"Narration cut"}),B.width>0&&f.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:D.map(H=>{if(H.type!=="speech")return null;const ge=B.x+kn(H.x,B.width),Te=B.y+kn(H.y,B.height),me=kn(H.width,B.width),He=kn(H.height,B.height),Le=N3(H,me,He),ht=H.tailAnchor?BS(ge,Te,me,He,H.tailAnchor,Le):null,it=Math.max(1.5,B.height*.004),Mt=H.id===U;return f.jsx("path",{"data-testid":`balloon-${H.id}`,d:A3(ge,Te,me,He,ht,Le),className:`fill-white/95 ${Mt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:Mt?it+.5:it,strokeLinejoin:"round"},H.id)})}),B.width>0&&D.map(H=>{const ge=B.x+kn(H.x,B.width),Te=B.y+kn(H.y,B.height),me=kn(H.width,B.width),He=kn(H.height,B.height),Le=H.id===U,ht=H.type==="speech",it=H.type==="narration",Mt=!!At[H.id];return f.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":Mt?"true":"false",onClick:Dt=>Ee(Dt,H.id),onMouseDown:Dt=>Be(Dt,H.id,"move"),className:`absolute rounded cursor-move select-none ${ht?"":`border-2 ${xM[H.type]}`} ${it?"bg-[#f4efe6]/85 rounded-md":""} ${Le&&!ht?"ring-2 ring-accent":""} ${Mt?"ring-2 ring-amber-500":""}`,style:{left:ge,top:Te,width:me,height:He},children:[(()=>{var ki,mi;const Dt=H.type==="sfx"?x:_;if(!H.text)return f.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Dt},children:yu[H.type]});const pi=H.type!=="sfx"&&!!H.speaker;if(!he)return f.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Dt,fontSize:Math.max(9,Math.min(He*.05,16)),fontWeight:((ki=H.textStyle)==null?void 0:ki.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:pi?`${H.speaker}: ${H.text}`:H.text});const kt=ru(Z(Dt),H.text,me,He,su(H,B.height,me,He));return f.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Dt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[pi&&f.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:kt.speakerFontSize,lineHeight:1.2},children:H.speaker}),f.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:kt.fontSize,lineHeight:`${kt.lineHeight}px`,fontWeight:((mi=H.textStyle)==null?void 0:mi.fontWeight)??400},children:kt.lines.map((Gt,mn)=>f.jsx("span",{className:"block",children:Gt},mn))})]})})(),Le&&f.jsx("div",{onMouseDown:Dt=>{Dt.stopPropagation(),Be(Dt,H.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${H.id}`})]},H.id)})]}),f.jsxs("div",{className:"w-52 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[Ve.length>0&&f.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),f.jsx("div",{className:"flex flex-col gap-1",children:Ve.map(H=>f.jsxs("button",{onClick:()=>oe(H),"data-testid":`script-insert-${H.key}`,title:`Add ${H.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[f.jsxs("span",{className:"font-medium text-accent",children:["+ ",yu[H.type]]})," ",f.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Ce?f.jsxs("div",{className:"space-y-3",children:[f.jsx("p",{className:"text-xs font-medium text-foreground",children:yu[Ce.type]}),Ce.speaker!==void 0&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),f.jsx("input",{value:Ce.speaker||"",onChange:H=>$(Ce.id,{speaker:H.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),f.jsx("textarea",{value:Ce.text,onChange:H=>$(Ce.id,{text:H.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),f.jsx("button",{onClick:()=>$(Ce.id,se(Ce)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((ne=Ce.textStyle)==null?void 0:ne.mode)==="manual"?f.jsx("button",{type:"button",onClick:()=>$(Ce.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):f.jsx("button",{type:"button",onClick:()=>ue(Ce),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((_e=Ce.textStyle)==null?void 0:_e.mode)==="manual"?f.jsxs("div",{className:"space-y-1.5",children:[f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),f.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Ce.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(H.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),f.jsxs("select",{value:String(Ce.textStyle.fontWeight??400),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",fontWeight:H.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[f.jsx("option",{value:"400",children:"Regular"}),f.jsx("option",{value:"700",children:"Bold"})]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),f.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Ce.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(H.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Ce.type!=="sfx"&&f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),f.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Ce.textStyle.speakerScale??.8).toFixed(2),onChange:H=>$(Ce.id,{textStyle:{...Ce.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(H.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):f.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Ce.type==="speech"&&(()=>{const H=Ce.tailAnchor||{x:.5,y:1.2};return f.jsxs("div",{className:"space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),f.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:_M.map(ge=>f.jsx("button",{type:"button",onClick:()=>$(Ce.id,{tailAnchor:ge.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${ge.key}`,children:ge.label},ge.key))}),f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",f.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:ge=>$(Ce.id,{tailAnchor:{...H,x:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),f.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",f.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:ge=>$(Ce.id,{tailAnchor:{...H,y:parseFloat(ge.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Ce.type!=="sfx"&&f.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Pe=Ce.bubbleStyle)==null?void 0:Pe.paddingX)??.06)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Fe=Ce.bubbleStyle)==null?void 0:Fe.paddingY)??.08)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),f.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Qe=Ce.bubbleStyle)==null?void 0:Qe.cornerRadius)??.4)*100).toFixed(0),onChange:H=>$(Ce.id,{bubbleStyle:{...Ce.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(H.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),f.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font: ",Ce.type==="sfx"?d.family:p.family]}),f.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[f.jsxs("p",{children:["x: ",Ce.x.toFixed(3),", y: ",Ce.y.toFixed(3)]}),f.jsxs("p",{children:["w: ",Ce.width.toFixed(3),", h: ",Ce.height.toFixed(3)]})]}),f.jsx("button",{onClick:()=>{W?be(Ce.id):G(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:W?"Click again to delete":"Delete"})]}):f.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const vM={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},yM="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",SM="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function wM(e){var a;const t=vM[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(SM),s.push(yM),s.join(` -`).trim()}function CM(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function cy(e,t){const i=CM(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",wM(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` -`)}function kM(e,t){const i=`${t}.cuts.json`,s=HS(e),a=s.length>0?s.map(o=>o.type==="speech"?`- speech — ${o.speaker||"Speaker"}: "${o.text}"`:o.type==="narration"?`- narration: ${o.text}`:`- sfx: ${o.text}`).join(` -`):"- (no dialogue/narration/SFX recorded for this cut — add a caption only if the scene needs one)";return[`Draft the speech bubbles and captions for cut ${e.id} of ${t}.`,"","Script to letter:",a,"","How to draft it:",`- Edit cut ${e.id}'s "overlays" array in ${i}: add one overlay per line above — "type":"speech" for dialogue (also set "speaker"), "narration" for captions, "sfx" for sound effects, with the line's text.`,"- Position each overlay with x, y, width, height as 0–1 fractions of the panel, roughly where it belongs over the art, and keep bubbles clear of faces.","- These are DRAFT positions only: do NOT export or upload. The writer reviews and adjusts them in the OWS lettering editor, then exports the final image there."].join(` -`)}const US=12e3,EM=5,NM=6e4,TM=6e4,jM=5;function AM(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function RM(e,t=US){return Math.min(t*2**e,NM)}const $S=e=>new Promise(t=>setTimeout(t,e));async function MM(e,t={}){var c;const i=t.sleep??$S,s=t.maxRetries??EM,a=t.baseDelayMs??US;let o=0;for(;;){const h=await e();if(h.ok||!AM(h.status,h.errorMessage)||o>=s)return h;const p=RM(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function DM(e={}){const t=e.limit??jM,i=e.windowMs??TM,s=e.sleep??$S,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const d=o[0]+i-a();d>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:d}),await s(d)),c()}o.push(a())}}const Dp=1024*1024;function uy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function BM(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await uy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Dp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await uy(e,"image/jpeg",s);if(a.size<=Dp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const LM=["image/webp","image/jpeg"];function FS(e){return LM.includes(e.type)&&e.size<=Dp}async function OM(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function qu(e){if(FS(e))return e;const t=await OM(e);return BM(t)}function zM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function PM(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter(zM):[]}async function IM(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function HM(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function UM(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function $M(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function FM({image:e,authFetch:t}){const i=HM(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?f.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):f.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function qM({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const D=await PM(e);E||o(D)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),y=Date.now(),N=async E=>{h(null),d(E.token);try{const D=await IM(e,E);await i(D)}catch(D){h(D instanceof Error?D.message:"Could not import the generated image")}finally{d(null)}},A=a!==null&&a.length>0;return f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),f.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),A&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"search",value:_,onChange:E=>x(E.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),f.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&f.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),A&&v.length===0&&f.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),A&&v.length>0&&f.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>f.jsxs("li",{"data-testid":`codex-image-${E.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[f.jsx(FM,{image:E,authFetch:e}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("p",{className:"text-[11px] text-foreground",children:[$M(E.mtimeMs,y)," · ",UM(E.size)]}),f.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),f.jsx("button",{onClick:()=>N(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&f.jsx("p",{className:"text-[11px] text-error",children:c})]})}const WM={done:"✓",current:"▸",todo:"○"};function GM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var N;if(!e||e.steps.length===0)return null;const p=IS(t),d=((N=e.steps.find(A=>A.key==="upload"))==null?void 0:N.status)==="done",_=d&&c&&!h,x=h||c?"done":d?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(A=>A.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],y=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode";return f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/50 space-y-2 flex-shrink-0","data-testid":"finish-episode-panel",children:[f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&f.jsxs("span",{className:"text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]})]}),f.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(A=>f.jsxs("li",{"data-testid":`finish-step-${A.key}`,"data-status":A.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${A.status==="current"?"border-accent/40 bg-accent/10 text-accent":A.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[f.jsx("span",{"aria-hidden":!0,children:WM[A.status]}),f.jsx("span",{children:A.label}),A.detail&&f.jsxs("span",{className:"text-muted",children:["· ",A.detail]})]},A.key))}),f.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-3 py-1 text-xs border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:y}),p.length>0&&f.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(A=>f.jsxs("div",{"data-testid":`finish-issue-group-${A.key}`,className:"text-[10px]",children:[f.jsx("p",{className:"font-medium text-amber-700",children:A.title}),f.jsx("ul",{className:"ml-3 list-disc text-muted",children:A.lines.map((E,D)=>f.jsx("li",{children:E},D))})]},A.key))})]})}function YM(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function qS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":Er(e)?"text":"missing"}const KM={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},VM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function XM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:Er(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function ZM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:d,syncing:_,staleMessages:x,onRepairStale:b,repairing:v,conversionPng:y,onConvert:N,converting:A,rowRef:E}){var De;const D=w.useRef(null),[P,J]=w.useState(!1),[q,L]=w.useState(null),[Z,he]=w.useState(!1),[ye,U]=w.useState(!1),[re,W]=w.useState(!1),[G,X]=w.useState(!1),[I,j]=w.useState("manual"),[O,B]=w.useState(!1),xe=qS(e),T=x.length>0,R=!!y,Y=w.useCallback(async()=>{y&&(X(!0),await N(e.id,y),X(!1),c())},[y,N,e.id,c]),C=w.useCallback(async Ee=>{J(!0),L(null);try{let Be=Ee;if(!FS(Ee))try{Be=await qu(Ee)}catch(tt){return L(tt instanceof Error?tt.message:"Could not import image"),!1}const je=Be.type==="image/jpeg"?"jpg":"webp",Ze=new FormData;Ze.append("file",new File([Be],`clean.${je}`,{type:Be.type}));const Ce=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ze});if(!Ce.ok){const tt=await Ce.json();return L(tt.error||"Upload failed"),!1}return c(),!0}catch{return L("Upload failed"),!1}finally{J(!1)}},[o,t,i,e.id,c]),se=XM(e,R,T),te=e.cleanImagePath??y??null,oe=((De=e.overlays)==null?void 0:De.length)??0,$=!Er(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!T&&!R,ue=w.useCallback(()=>{var Ee;(Ee=navigator.clipboard)==null||Ee.writeText(kM(e,i)),B(!0),setTimeout(()=>B(!1),2e3)},[e,i]),be=se.key==="convert"?{label:G?"Converting…":"Convert image",onClick:Y,testid:`card-convert-${e.id}`}:se.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:se.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:se.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null;return f.jsxs("div",{ref:E,"data-cut-row":e.id,className:`border rounded ${s?"border-accent/30":"border-border"}`,children:[f.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[f.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[f.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${VM[se.tone]}`}),f.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),f.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${KM[se.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:se.label})]}),te?f.jsx(Rp,{storyName:t,assetPath:te,authFetch:o,alt:`Cut ${e.id} artwork`,className:"w-full max-h-44 object-contain rounded border border-border bg-white"}):f.jsx("div",{className:"w-full h-20 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:Er(e)?"Text panel — no artwork needed":"No artwork yet"}),f.jsx("button",{onClick:a,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),$&&f.jsxs("div",{className:"space-y-1","data-testid":`lettering-${e.id}`,children:[f.jsx("div",{className:"text-[10px] font-medium text-muted uppercase tracking-wider",children:"Lettering"}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="manual",onChange:()=>j("manual"),"data-testid":`lettering-mode-manual-${e.id}`}),"Manual — I place bubbles myself"]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-foreground",children:[f.jsx("input",{type:"radio",name:`lettering-mode-${e.id}`,checked:I==="ai",onChange:()=>j("ai"),"data-testid":`lettering-mode-ai-${e.id}`}),"AI draft — ask the agent to place initial bubbles"]}),I==="ai"&&f.jsx("p",{className:"text-[10px] text-muted",children:"Paste it to your agent, then review the draft bubbles here and export the final cut."})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[$?I==="manual"?f.jsx("button",{onClick:h,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:oe>0?"Review lettering":"Add speech bubbles"}):f.jsx("button",{onClick:ue,"data-testid":`copy-lettering-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded border border-accent/40 text-accent hover:bg-accent/5",children:O?"Copied!":"Copy AI lettering prompt"}):be?f.jsx("button",{onClick:be.onClick,disabled:se.key==="convert"&&(G||A),"data-testid":be.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:be.label}):null,f.jsx("button",{onClick:a,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:s?"Hide details":"Open details"})]})]}),s&&f.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[R&&f.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[f.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),f.jsx("button",{onClick:Y,disabled:G||A,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:G?"Converting…":"Convert image"})]}),T&&!R&&f.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[x.map((Ee,Be)=>f.jsx("p",{className:"text-[11px] text-error",children:Ee},Be)),f.jsx("button",{onClick:b,disabled:v,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:v?"Repairing…":"Clear stale path"})]}),!Er(e)&&f.jsxs("div",{className:"mt-2 space-y-2",children:[f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(cy(e,i)),he(!0),setTimeout(()=>he(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:Z?"Copied!":"Copy Codex task"}),f.jsx("input",{ref:D,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ee=>{var je;const Be=(je=Ee.target.files)==null?void 0:je[0];Be&&C(Be),Ee.target.value=""}}),f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("button",{onClick:()=>{var Ee;return(Ee=D.current)==null?void 0:Ee.click()},disabled:P,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:P?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),f.jsx("button",{onClick:()=>W(Ee=>!Ee),disabled:P,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:re?"Hide Codex images":"Import from Codex"})]}),re&&f.jsx(qM,{authFetch:o,cutId:e.id,onImport:async Ee=>{await C(Ee)&&W(!1)},onClose:()=>W(!1)}),!e.cleanImagePath&&f.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),xe==="missing"&&f.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[f.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),f.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",f.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(cy(e,i)),U(!0),setTimeout(()=>U(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:ye?"Copied!":"Copy Codex task"})]}),xe==="missing"&&p&&f.jsx("button",{onClick:d,disabled:_,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:_?"Syncing...":"Found local clean image — sync to cut plan"}),q&&f.jsx("p",{className:"text-xs text-error mt-1",children:q})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||Er(e))&&f.jsx("button",{onClick:h,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&f.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&f.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ee,Be)=>f.jsxs("p",{children:[f.jsxs("span",{className:"font-medium",children:[Ee.speaker,":"]})," ",Ee.text]},Be))}),e.narration&&f.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function hy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h}){var Gt,mn;const[p,d]=w.useState(null),_=w.useRef(o);_.current=o;const x=w.useRef(h);x.current=h;const[b,v]=w.useState(!0),[y,N]=w.useState(null),[A,E]=w.useState(null),[D,P]=w.useState(null),[J,q]=w.useState(!1),[L,Z]=w.useState([]),[he,ye]=w.useState(!1),[U,re]=w.useState(""),[W,G]=w.useState({markdownReady:!1,published:!1}),[X,I]=w.useState(!1),[j,O]=w.useState(!1),[B,xe]=w.useState(!1),[T,R]=w.useState(null),[Y,C]=w.useState(null),[se,te]=w.useState(new Set),[oe,$]=w.useState(new Map),[ue,be]=w.useState(!1),[De,Ee]=w.useState(null),[Be,je]=w.useState(!1),[Ze,Ce]=w.useState(null),tt=w.useRef(new Map),pt=w.useRef(null),Ge=t.replace(/\.md$/,"");w.useEffect(()=>{var de;c&&pt.current!==c.seq&&(pt.current=c.seq,c.openEditor?P(c.cutId):(E(c.cutId),Ce(c.cutId)),(de=x.current)==null||de.call(x))},[c]),w.useEffect(()=>{var Re;if(Ze==null)return;const de=tt.current.get(Ze);de&&((Re=de.scrollIntoView)==null||Re.call(de,{behavior:"smooth",block:"center"}),Ce(null))},[Ze,p]);const Ae=w.useCallback(async()=>{var de;try{const Re=await i(`/api/stories/${e}/cuts/${Ge}`);if(Re.status===404){d(null);return}if(!Re.ok){const st=await Re.json();N(st.error||"Failed to load cuts");return}const We=await Re.json();d(We),N(null);try{const st=await i(`/api/stories/${e}/${t}`);if(st.ok){const nt=await st.json(),ct=typeof(nt==null?void 0:nt.content)=="string"?nt.content:"",ae=Array.isArray(We==null?void 0:We.cuts)?We.cuts:[],we=ct.length>0&&zS(ct,ae).ready,ze=(nt==null?void 0:nt.status)==="published"||(nt==null?void 0:nt.status)==="published-not-indexed";G({markdownReady:we,published:ze})}else G({markdownReady:!1,published:!1})}catch{G({markdownReady:!1,published:!1})}(de=_.current)==null||de.call(_)}catch{N("Failed to load cuts")}finally{v(!1)}},[i,e,Ge,t]),Ve=w.useCallback(async()=>{be(!1);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/detect-clean-images`);if(!de.ok)return;const Re=await de.json();te(new Set(Array.isArray(Re.detected)?Re.detected:[]));const We=new Map,st=Re.stale;if(Array.isArray(st))for(const nt of st){if(typeof(nt==null?void 0:nt.cutId)!="number"||typeof(nt==null?void 0:nt.message)!="string")continue;const ct=We.get(nt.cutId)??[];ct.push(nt.message),We.set(nt.cutId,ct)}$(We),be(!0)}catch{}},[i,e,Ge]),At=w.useCallback(async()=>{Ee(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/asset-diagnostics`);if(!de.ok)return;const Re=await de.json();Ee(Array.isArray(Re.diagnostics)?Re.diagnostics:null)}catch{}},[i,e,Ge]),Ot=w.useCallback(async()=>{je(!0);try{await Promise.all([Ae(),Ve(),At()])}finally{je(!1)}},[Ae,Ve,At]),ci=w.useCallback(async()=>{I(!0),C(null),Z([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/sync-clean-images`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Sync failed");else{const We=Array.isArray(Re.synced)?Re.synced.length:0,st=Array.isArray(Re.cleared)?Re.cleared.length:0,nt=Array.isArray(Re.rejected)?Re.rejected:[];nt.length>0&&Z(nt.map(ae=>`Cut ${ae.cutId}: ${ae.reason}`));const ct=[];We>0&&ct.push(`Synced ${We}`),st>0&&ct.push(`Cleared ${st} stale path${st===1?"":"s"}`),C(ct.length>0?ct.join(", "):"No new clean images"),await Ae(),await Ve(),await At()}}catch{C("Sync failed")}I(!1)},[i,e,Ge,Ae,Ve,At]),St=w.useCallback(async(de,Re)=>{try{const We=await i(AS(e,Re));if(!We.ok)return!1;const st=await We.blob(),nt=await qu(new File([st],"clean.png",{type:st.type||"image/png"})),ct=nt.type==="image/jpeg"?"jpg":"webp",ae=new FormData;return ae.append("file",new File([nt],`clean.${ct}`,{type:nt.type})),(await i(`/api/stories/${e}/cuts/${Ge}/upload-clean/${de}`,{method:"POST",body:ae})).ok}catch{return!1}},[i,e,Ge]),fi=w.useCallback(async de=>{xe(!0),R(null);let Re=0;const We=[];for(const st of de)await St(st.cutId,st.pngPath)?Re++:We.push(st.cutId);await Ot(),xe(!1),R(We.length===0?`Converted ${Re} image${Re===1?"":"s"} to WebP`:`Converted ${Re}; ${We.length} failed (Cut ${We.join(", ")}) — try Convert image on each`)},[St,Ot]),ne=w.useCallback(async()=>{var nt;if(!p)return;ye(!0),re(""),Z([]);const de=p.cuts.filter(ct=>ct.finalImagePath&&!ct.uploadedCid),Re=[],We=DM({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:ct})=>re(`Upload limit reached — waiting ${Math.round(ct/1e3)}s before continuing…`)});for(let ct=0;ct{const Xe=await i("/api/publish/upload-plot-image",{method:"POST",body:_t});if(Xe.ok){const{cid:qt,url:gi}=await Xe.json();return{ok:!0,status:Xe.status,cid:qt,url:gi}}const zt=await Xe.json().catch(()=>({}));return{ok:!1,status:Xe.status,errorMessage:zt.error}},{...a,onWaiting:({attempt:Xe,maxRetries:zt,waitMs:qt})=>re(`Cut ${ae.id} rate-limited — waiting ${Math.round(qt/1e3)}s before retry ${Xe}/${zt}...`)});if(!Je.ok){Re.push(`Cut ${ae.id}: upload failed — ${Je.errorMessage||"unknown"}`);continue}const{cid:ut,url:at}=Je;(await i(`/api/stories/${e}/cuts/${Ge}/set-uploaded/${ae.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:ut,url:at})})).ok||Re.push(`Cut ${ae.id}: failed to record upload`)}catch(we){Re.push(`Cut ${ae.id}: ${we instanceof Error?we.message:"failed"}`)}}if(Re.length>0){Z(Re),ye(!1),re(""),Ae();return}re("Preparing episode for publishing…");const st=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(st.ok){const ct=await st.json();((nt=ct.warnings)==null?void 0:nt.length)>0&&Z(ct.warnings)}ye(!1),re(""),Ae()},[p,i,e,Ge,a,Ae]),_e=w.useCallback(async()=>{O(!0),C(null);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/repair-asset-paths`,{method:"POST"}),Re=await de.json().catch(()=>({}));if(!de.ok)C(Re.error||"Repair failed");else{const We=Array.isArray(Re.cleared)?Re.cleared.length:0;C(We>0?`Cleared ${We} stale path${We===1?"":"s"}`:"No stale paths to clear"),await Ae(),await Ve()}}catch{C("Repair failed")}O(!1)},[i,e,Ge,Ae,Ve]),[Pe,Fe]=w.useState(!1),Qe=w.useCallback(async()=>{if(p){Fe(!0);try{const de=p.cuts.reduce((nt,ct)=>Math.max(nt,ct.id),0)+1,Re={id:de,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},We={...p,cuts:[...p.cuts,Re]},st=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(We)});if(st.ok)E(de),await Ae();else{const nt=await st.json().catch(()=>({}));C(nt.error||"Could not add text panel")}}catch{C("Could not add text panel")}Fe(!1)}},[p,i,e,Ge,Ae]);if(w.useEffect(()=>{Ae(),Ve(),At()},[Ae,Ve,At]),b)return f.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(y)return f.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[f.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),f.jsx("p",{className:"text-xs text-error",children:y}),f.jsxs("p",{className:"text-xs text-muted",children:[Ge,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),f.jsx("button",{onClick:Ae,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!p||p.cuts.length===0)return f.jsxs("div",{className:"p-4 text-center space-y-1",children:[f.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),f.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const H=D!==null?p.cuts.find(de=>de.id===D):null;if(H)return f.jsx(bM,{storyName:e,cut:H,plotFile:Ge,language:s,authFetch:i,onSave:async de=>{const Re={...p,cuts:p.cuts.map(st=>st.id===D?{...st,overlays:de}:st)},We=await i(`/api/stories/${e}/cuts/${Ge}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Re)});if(!We.ok){const st=await We.json().catch(()=>({}));throw new Error(st.error||"Failed to save overlays")}},onExported:()=>Ae(),onClose:()=>{P(null),Ae()}});const ge=p.cuts.reduce((de,Re)=>{const We=qS(Re);return de[We]++,de},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),Te=p.cuts.filter(de=>!Er(de)).length,me=p.cuts.filter(de=>LS(de)).map(de=>de.id),He=eM({cuts:p.cuts,published:W.published}),Le=((Gt=He.steps.find(de=>de.key==="upload"))==null?void 0:Gt.status)==="done",ht=p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)||Le&&!W.markdownReady,it=(De??[]).filter(de=>de.state==="needs-conversion"&&de.convertiblePng).map(de=>({cutId:de.cutId,pngPath:de.convertiblePng})),Mt=new Map(it.map(de=>[de.cutId,de.pngPath])),Dt=(De??[]).filter(de=>de.state==="needs-conversion"&&de.issue).map(de=>de.issue),pi=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mn=Ge.match(/\d+/))==null?void 0:mn[0])??"0",10)+1}`,kt=typeof p.title=="string"?p.title:null,ki=p.cuts.filter(de=>!Er(de)),mi={cuts:p.cuts.length,artwork:ki.filter(de=>de.cleanImagePath||Mt.has(de.id)).length,converted:ki.filter(de=>de.cleanImagePath&&/\.(webp|jpe?g)$/i.test(de.cleanImagePath)).length,lettered:p.cuts.filter(de=>{var Re;return(((Re=de.overlays)==null?void 0:Re.length)??0)>0||!!de.finalImagePath}).length,uploaded:p.cuts.filter(de=>de.uploadedCid||de.uploadedUrl).length};return f.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[f.jsxs("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"font-serif text-foreground truncate",children:pi}),kt&&f.jsxs("span",{className:"text-muted truncate",children:["· ",kt]})]}),f.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[mi.cuts," cuts · ",mi.artwork," artwork found · ",mi.converted," converted · ",mi.lettered," lettered · ",mi.uploaded," uploaded"]})]}),f.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[f.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),f.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[f.jsxs("span",{className:"font-mono text-muted",children:[p.cuts.length," cuts"]}),ge.missing>0&&f.jsxs("span",{className:"text-muted",children:[ge.missing," missing"]}),ge.clean>0&&f.jsxs("span",{className:"text-green-700",children:[ge.clean," clean"]}),ge.lettered>0&&f.jsxs("span",{className:"text-amber-700",children:[ge.lettered," lettered"]}),ge.uploaded>0&&f.jsxs("span",{className:"text-green-700",children:[ge.uploaded," uploaded"]}),ge.text>0&&f.jsxs("span",{className:"text-accent",children:[ge.text," text ",ge.text===1?"panel":"panels"]}),f.jsx("button",{onClick:async()=>{q(!0),Z([]);try{const de=await i(`/api/stories/${e}/cuts/${Ge}/generate-markdown`,{method:"POST"});if(de.ok){const Re=await de.json();Z(Re.warnings||[])}}catch{}q(!1)},disabled:J,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:J?"Preparing…":"Prepare episode for publish"}),f.jsx("button",{onClick:Qe,disabled:Pe,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:Pe?"Adding…":"Add narration/text panel"}),f.jsx("button",{onClick:Ot,disabled:Be,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:Be?"Checking…":"Refresh assets"}),f.jsx("button",{onClick:ci,disabled:X,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:X?"Syncing...":"Sync clean images"}),f.jsx("button",{onClick:ne,disabled:he||!(p!=null&&p.cuts.some(de=>de.finalImagePath&&!de.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:U||"Upload & Prepare for Publish"})]})]}),f.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),f.jsx("span",{"aria-hidden":!0,children:"→"}),f.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",f.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," for a narration or title card. It becomes a solid card exported as a final image."]})]}),me.length>0&&f.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[me.length===1?"Cut":"Cuts"," ",me.join(", ")," ",me.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export ",me.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),ue&&Te>0&&ge.missing===0&&oe.size===0&&f.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[f.jsx("span",{"aria-hidden":!0,children:"✓"}),f.jsxs("span",{children:["All ",Te," clean image",Te===1?"":"s"," present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),Y&&f.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:Y}),it.length>0&&f.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[it.length," PNG image",it.length===1?"":"s"," found"]}),f.jsx("button",{onClick:()=>fi(it),disabled:B,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:B?"Converting…":"Convert all to WebP"})]}),f.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),T&&f.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:T}),Dt.length>0&&f.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[f.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Dt.map((de,Re)=>f.jsx("li",{children:de},Re))})]})]}),De&&De.length>0&&(()=>{const de=YM(De),Re=De.filter(We=>We.state==="missing");return f.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[f.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",de.uploaded," uploaded · ",de.finalReady," final · ",de.cleanReady," clean · ",de.planned," planned",de.needsConversion>0?` · ${de.needsConversion} needs conversion`:"",de.missing>0?` · ${de.missing} missing`:""]}),Re.length>0&&f.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:Re.map(We=>f.jsx("li",{children:We.issue},We.cutId))})]})})(),f.jsx(GM,{checklist:He,issues:L,onFinish:ne,finishing:he,progressText:U,canFinish:ht,markdownReady:W.markdownReady,published:W.published}),f.jsx("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-2","data-testid":"cut-list-scroll",children:p.cuts.map(de=>f.jsx(ZM,{cut:de,storyName:e,plotFile:Ge,expanded:A===de.id,onToggle:()=>E(A===de.id?null:de.id),authFetch:i,onUpdated:()=>{Ae(),Ve(),At()},onOpenEditor:()=>P(de.id),detectedLocalClean:se.has(de.id),onSyncClean:ci,syncing:X,staleMessages:oe.get(de.id)??[],onRepairStale:_e,repairing:j,conversionPng:Mt.get(de.id)??null,onConvert:St,converting:B,rowRef:Re=>{Re?tt.current.set(de.id,Re):tt.current.delete(de.id)}},de.id))})]})}function xm({coach:e,onAction:t,className:i="",showEmptyState:s=!1}){const[a,o]=w.useState(null),c=a!==null&&a===(e==null?void 0:e.prompt);return e===void 0?null:e?f.jsx("div",{className:`m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm ${i}`,"data-testid":"workflow-coach","data-stage":e.stageLabel,"data-action-kind":e.actionKind,"data-ui-action":e.uiAction??"",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent","data-testid":"workflow-coach-stage",children:e.stageLabel}),f.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"workflow-coach-action",children:[f.jsx("span",{className:"font-semibold",children:"Next: "}),f.jsx("span",{children:e.action})]}),c&&f.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:"Prompt copied."})]}),e.actionKind==="agent"&&e.prompt?f.jsx("button",{onClick:()=>{var p;if(!e.prompt)return;const h=e.prompt;(p=navigator.clipboard)==null||p.writeText(h).then(()=>o(h)).catch(()=>{})},"data-testid":"workflow-coach-copy",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):e.actionKind==="ui"&&e.uiAction?f.jsx("button",{onClick:()=>t(e.uiAction,e.episodeFile),"data-testid":"workflow-coach-do",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):null]})}):s?f.jsx("div",{className:`m-3 rounded-lg border border-green-700/25 bg-green-950/5 px-4 py-3 ${i}`,"data-testid":"workflow-coach","data-state":"complete",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("span",{className:"rounded-full bg-green-700/10 px-2 py-1 text-[10px] font-bold uppercase tracking-[0.16em] text-green-700",children:"Complete"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No next action available"}),f.jsx("p",{className:"mt-0.5 text-xs text-muted",children:"This workflow has no queued next step right now."})]})]})}):null}function QM({storyName:e,fileName:t,authFetch:i,refreshKey:s=0,onAction:a,showEmptyState:o=!1}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,t??"",s]),[d,_]=w.useState(null);return d!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=t?`?focus=${encodeURIComponent(t)}`:"";return i(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h((v==null?void 0:v.coach)??null)}).catch(()=>{}),()=>{x=!0}},[e,t,i,s]),f.jsx(xm,{coach:c,onAction:a,showEmptyState:o})}const JM=1024*1024,eD=["image/webp","image/jpeg"],tD="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function iD(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function dy(e){return e.size>JM?"Image exceeds 1MB limit":eD.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function nD(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Bp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function rD(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function jo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function sD(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Lp(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function _m(e){var s;const t=Bp(e.fileContent);if(t)return!Lp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Lp(i)}function bm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Bp(i);if(t==="genesis.md"){const p=a?Bp(a):null;return(h??p??rD(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),d=sD(t);return((p||d)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function aD(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function lD(e){return aD(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function fy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function oD(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Mf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Df(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function cD(e){return!!e&&e.ready===!1}function uD(e){const t=Df(e.requiredBalance)??Df(e.creationFee),i=Df(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const hD={...ll,attributes:{...ll.attributes,img:["src","alt","title"]}},dD="https://ipfs.filebase.io/ipfs/";function fD(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function pD(e){const t=fD(e),i=[];for(const a of t)a.url.startsWith(dD)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function mD({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:d,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v}){const[y,N]=w.useState(null),[A,E]=w.useState(!1),[D,P]=w.useState("preview"),[J,q]=w.useState("publish"),[L,Z]=w.useState("text"),[he,ye]=w.useState(null),U=w.useCallback((ee,Se)=>{P("edit"),ye(Ne=>({cutId:ee,openEditor:Se,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[re,W]=w.useState(""),[G,X]=w.useState(!1),[I,j]=w.useState(!1),[O,B]=w.useState(!1),[xe,T]=w.useState(null),[R,Y]=w.useState(""),[C,se]=w.useState(""),[te,oe]=w.useState(!1),[$,ue]=w.useState(null),[be,De]=w.useState(0),[Ee,Be]=w.useState(0),[je,Ze]=w.useState(null),[Ce,tt]=w.useState(null),[pt,Ge]=w.useState(null),[Ae,Ve]=w.useState(0),At=w.useRef(null),Ot=w.useRef(!1),[ci,St]=w.useState(!1),[fi,ne]=w.useState(nl[0]),[_e,Pe]=w.useState(Xr[0]),[Fe,Qe]=w.useState(!1),[H,ge]=w.useState(null),[Te,me]=w.useState(null),[He,Le]=w.useState(!1),[ht,it]=w.useState(!1),[Mt,Dt]=w.useState(!1),[pi,kt]=w.useState(null),[ki,mi]=w.useState(!1),Gt=w.useRef(null),mn=w.useRef(null),[de,Re]=w.useState(!1),[We,st]=w.useState(null),[nt,ct]=w.useState(null),[ae,we]=w.useState("unknown"),ze=w.useRef(!1),[Rt,_t]=w.useState(!1),[Je,ut]=w.useState(!1),[at,wt]=w.useState(null),[Xe,zt]=w.useState([]),[qt,gi]=w.useState(null),Tn=w.useRef(null),mr=w.useRef(null),$i=w.useCallback(async()=>{if(!e||!t){N(null);return}const ee=`${e}/${t}`,Se=mr.current!==ee;Se&&(mr.current=ee);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Ke=await Ne.json();N(Ke),(Se||!Ot.current)&&(W(Ke.content??""),Se&&(j(!1),Ot.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{E(!0),$i().finally(()=>E(!1))},[$i]),w.useEffect(()=>{if(!e||!t||D==="edit"&&I)return;const ee=setInterval($i,3e3);return()=>clearInterval(ee)},[e,t,$i,D,I]);const[ei,jn]=w.useState(null),Fn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Fn||!e){jn(null);return}let ee=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||jn(Se?Mp(Se.cuts||[]):null)}).catch(()=>{ee||jn(null)}),()=>{ee=!0}},[Fn,e,i]);const ti=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!ti||!e||!t){ue(null),De(0),Be(0),Ze(null);return}let ee=!1;const Se=t.replace(/\.md$/,"");return Ze(null),(async()=>{try{const[Ne,Ke]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Se}`)]);if(ee)return;if(!Ke.ok){ue("error"),De(0),Be(0),Ze(null);return}const Et=await Ke.json(),xi=Et.cuts||[],Rn=Ne.ok?(await Ne.json()).content??"":"",on=PS(Rn,xi);ee||(ue(on.stage),De(on.awaitingCount),Be(on.totalCuts),Ze(Mp(xi)),Ge(typeof Et.title=="string"?Et.title:null))}catch{ee||(ue("error"),De(0),Be(0),Ze(null))}})(),()=>{ee=!0}},[ti,e,t,i,y==null?void 0:y.content,y==null?void 0:y.status,Ae]),w.useEffect(()=>{if(!e){tt(null);return}let ee=!1;return i(`/api/stories/${e}/structure.md`).then(Se=>Se.ok?Se.json():null).then(Se=>{ee||tt((Se==null?void 0:Se.content)??null)}).catch(()=>{}),()=>{ee=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ee=bu(p);let Se=ee??"";if(!ee&&Ce){const Ke=Ce.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Ke&&(Se=bu(Ke[1].replace(/\*+/g,"").trim())??"")}Y(Se);let Ne=h&&Xr.find(Ke=>Ke.toLowerCase()===h.toLowerCase())||"";if(!Ne&&Ce){const Ke=Ce.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Ke&&(Ne=Xr.find(Et=>Et.toLowerCase()===Ke[1].replace(/\*+/g,"").trim().toLowerCase())||"")}se(Ne),oe(d??!1)},[e,p,h,d,Ce]);const Yt=w.useCallback(ee=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}).catch(()=>{})},[e,i]),qn=w.useCallback(async()=>{if(!(!e||!t)){X(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:re})})).ok&&(j(!1),Ot.current=!1,N(Se=>Se&&{...Se,content:re}))}catch{}X(!1)}},[e,t,i,re]),sn=w.useCallback(async()=>{if(!e||!t)return;const ee=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ee}/generate-markdown`,{method:"POST"})).ok&&(await $i(),Ve(Ne=>Ne+1))}catch{}},[e,t,i,$i]),An=w.useCallback((ee,Se)=>{if(ee==="view-progress"){x==null||x();return}if(Se&&Se!==t){b==null||b(Se);return}switch(ee){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":P("edit"),Z("cuts");break;case"generate-markdown":sn();break;case"publish":P("preview");break}},[t,x,b,sn]),ts=w.useCallback(ee=>{var Ke;const Se=(Ke=ee.target.files)==null?void 0:Ke[0];if(!Se)return;ze.current=!0,st(null),ct(null);const Ne=dy(Se);if(Ne){ge(null),me(Et=>(Et&&URL.revokeObjectURL(Et),null)),Gt.current&&(Gt.current.value=""),kt(Ne),we("invalid");return}ge(Se),me(Et=>(Et&&URL.revokeObjectURL(Et),URL.createObjectURL(Se))),kt(null),we("selected")},[]),Zt=w.useCallback(async ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];if(mn.current&&(mn.current.value=""),!(!Se||!e)){ze.current=!0,st(null),Re(!0),kt(null);try{let Ke;try{Ke=await qu(Se)}catch(cr){ge(null),me(Ls=>(Ls&&URL.revokeObjectURL(Ls),null)),kt(cr instanceof Error?cr.message:"Could not import image");return}const Et=Ke.type==="image/jpeg"?"jpg":"webp",xi=new File([Ke],`cover.${Et}`,{type:Ke.type}),Rn=new FormData;Rn.append("file",xi);const on=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Rn});if(!on.ok){const cr=await on.json().catch(()=>({}));kt(cr.error||"Cover import failed");return}ge(xi),me(cr=>(cr&&URL.revokeObjectURL(cr),URL.createObjectURL(xi))),ct(null),we("selected"),kt(null)}catch{kt("Cover import failed")}finally{Re(!1)}}},[e,i]),gn=w.useCallback(async ee=>{if(ee.size>1024*1024){wt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ee.type)){wt("Only WebP and JPEG images are accepted");return}ut(!0),wt(null);try{const Ne=new FormData;Ne.append("file",ee);const Ke=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Ke.ok){const xi=await Ke.json();throw new Error(xi.error||"Upload failed")}const Et=await Ke.json();zt(xi=>[...xi,{cid:Et.cid,url:Et.url}])}catch(Ne){wt(Ne instanceof Error?Ne.message:"Upload failed")}finally{ut(!1),Tn.current&&(Tn.current.value="")}},[i]),dl=w.useCallback(ee=>{var Ne;const Se=(Ne=ee.target.files)==null?void 0:Ne[0];Se&&gn(Se)},[gn]),Ar=w.useCallback(async()=>{if(y!=null&&y.storylineId){Le(!0),kt(null),mi(!1);try{let ee;if(H){const Ne=new FormData;Ne.append("file",H);const Ke=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Ke.ok){const xi=await Ke.json();throw new Error(xi.error||"Cover upload failed")}ee=(await Ke.json()).cid}const Se=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:y.storylineId,...ee!==void 0&&{coverCid:ee},genre:fi,language:_e,isNsfw:Fe})});if(!Se.ok){const Ne=await Se.json();throw new Error(Ne.error||"Update failed")}mi(!0),ge(null),ee!==void 0&&(Dt(!0),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),we("unknown"),Gt.current&&(Gt.current.value="")),setTimeout(()=>mi(!1),3e3)}catch(ee){kt(ee instanceof Error?ee.message:"Update failed")}finally{Le(!1)}}},[y==null?void 0:y.storylineId,H,fi,_e,Fe,i]);w.useEffect(()=>{St(!1),ge(null),me(null),kt(null),mi(!1),it(!1),_t(!1),zt([]),wt(null),st(null),ct(null),we("unknown"),ze.current=!1,Z("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!y||y.storylineId||y.status==="published"||y.status==="published-not-indexed"||ze.current)return;let ee=!1;return(async()=>{try{const Se=await i(`/api/stories/${e}/cover-asset`);if(ee||!Se.ok)return;const Ne=await Se.json();if(ee)return;if(!(Ne!=null&&Ne.found)){we("none");return}if(!Ne.valid){ct(Ne.error||"Detected cover asset is invalid and was not used"),we("invalid");return}const Ke=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ee||!Ke.ok)return;const Et=await Ke.blob(),xi=new File([Et],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(dy(xi)||ee||ze.current)return;ge(xi),me(Rn=>(Rn&&URL.revokeObjectURL(Rn),URL.createObjectURL(xi))),st(Ne.path),we("detected")}catch{}})(),()=>{ee=!0}},[e,t,y,y==null?void 0:y.status,y==null?void 0:y.storylineId,i]),w.useEffect(()=>{if(!ci||!(y!=null&&y.storylineId))return;it(!1);const ee="https://plotlink.xyz";let Se=!1;return fetch(`${ee}/api/storyline/${y.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!Se){if(!Ne){kt("Could not load current story metadata");return}if(Ne.genre){const Ke=bu(Ne.genre);Ke&&ne(Ke)}if(Ne.language){const Ke=Xr.find(Et=>Et.toLowerCase()===Ne.language.toLowerCase());Ke&&Pe(Ke)}Ne.isNsfw!==void 0&&Qe(!!Ne.isNsfw),Dt(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),it(!0)}}).catch(()=>{Se||kt("Could not load current story metadata")}),()=>{Se=!0}},[ci,y==null?void 0:y.storylineId]),w.useEffect(()=>{if(D!=="edit")return;const ee=Se=>{(Se.metaKey||Se.ctrlKey)&&Se.key==="s"&&(Se.preventDefault(),qn())};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[D,qn]),w.useEffect(()=>{if((y==null?void 0:y.status)!=="published-not-indexed"||!y.publishedAt)return;const ee=new Date(y.publishedAt).getTime(),Se=300*1e3,Ne=()=>{const Et=Math.max(0,Se-(Date.now()-ee));T(Et)};Ne();const Ke=setInterval(Ne,1e3);return()=>clearInterval(Ke)},[y==null?void 0:y.status,y==null?void 0:y.publishedAt]);const ar=xe!==null&&xe<=0,xn=xe!==null&&xe>0?`${Math.floor(xe/6e4)}:${String(Math.floor(xe%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:f.jsxs("div",{className:"text-center",children:[f.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),f.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(A&&!y)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const ha=(D==="edit"?re:(y==null?void 0:y.content)??"").length,Zi=t==="genesis.md",lr=t?/^plot-\d+\.md$/.test(t):!1,Qi=c==="cartoon"&&lr,an=c==="cartoon"&&Zi,da=an||Qi,Ei=(y==null?void 0:y.status)==="published"||(y==null?void 0:y.status)==="published-not-indexed",fa=an?ei?ei.total:null:Qi?$===null?null:Ee:null,pa=iM({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Ei,cutCount:fa,cutProgress:an?ei:null}),ma=(an||Qi)&&!Ei,Wn=ma?bm({fileName:t,fileContent:(y==null?void 0:y.content)??"",storySlug:e??"",structureContent:Ce,contentType:"cartoon",episodeTitle:pt}):null,ga=!!Wn&&jo(Wn,t),fl=Qi&&!Ei&&!_m({fileContent:(y==null?void 0:y.content)??"",episodeTitle:pt}),Gn=an&&!Ei?mm((y==null?void 0:y.content)??""):null,Po=!!Gn&&Gn.blockers.length>0,Io="w-full max-w-[32rem] rounded-xl border px-3 py-3",Ho={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},xa=ee=>{if(!an)return null;const Se=iD({hasSelectedCover:!!H,invalid:ae==="invalid",attached:ee});return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Se.state,children:[f.jsx("span",{className:`text-[11px] font-medium ${Ho[Se.tone]}`,children:Se.label}),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),f.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:tD})]})]})},pl=ga||fl,Wu=()=>{if(!ma||!Wn)return null;const ee=Zi?"Story title":"Episode title";return f.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":ga?"true":"false","data-blocked":pl?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[ee,":"]})," ",f.jsx("span",{className:pl?"text-error font-medium":"text-foreground",children:Wn})]}),ga?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Zi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):fl?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Wn,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},_a=()=>Gn?f.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Po?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),Gn.blockers.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ee},`b-${Se}`)),Gn.warnings.map((ee,Se)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ee},`w-${Se}`))]}):null,ln=Zi||lr?1e4:null,is=!Ei&&ln!==null&&ha>ln,ml=(y==null?void 0:y.content)??"",or=Ei?{count:0,warnings:[]}:pD(ml),Rr=f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsx("textarea",{ref:At,value:re,onChange:ee=>{W(ee.target.value),j(!0),Ot.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),f.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-muted",children:I?"Unsaved changes":"No changes"}),f.jsx("button",{onClick:qn,disabled:!I||G,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:G?"Saving...":"Save"})]})]});return f.jsxs("div",{className:"h-full flex flex-col",children:[f.jsxs("div",{className:"border-b border-border",children:[f.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&f.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),f.jsxs("span",{children:[e,"/",t]}),(y==null?void 0:y.status)==="published"&&f.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(y==null?void 0:y.status)==="published-not-indexed"&&f.jsx("span",{className:"text-amber-700 font-medium",title:y.indexError,children:"Published (not indexed)"}),(y==null?void 0:y.status)==="pending"&&f.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:`text-xs font-mono ${is?"text-error font-medium":"text-muted"}`,children:[ha.toLocaleString(),ln!==null?`/${ln.toLocaleString()}`:" chars"]}),is&&f.jsxs("span",{className:"text-error text-xs font-medium",children:[(ha-ln).toLocaleString()," over limit"]})]})]}),f.jsxs("div",{className:"flex px-3 gap-1",children:[f.jsx("button",{onClick:()=>P("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),f.jsxs("button",{onClick:()=>P("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",I&&f.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),c==="cartoon"&&e&&t&&f.jsx(QM,{storyName:e,fileName:t,authFetch:i,refreshKey:Ae,onAction:An,showEmptyState:!0}),D==="preview"?Qi?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>q("publish"),className:`px-2 py-0.5 text-[11px] rounded ${J==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),f.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>q("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${J==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:J==="publish"?f.jsx(aM,{content:(y==null?void 0:y.content)??"",stage:$}):f.jsx(F3,{storyName:e,fileName:t,authFetch:i,onEditCut:U})})]}):f.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:y!=null&&y.content?f.jsx("div",{className:"prose max-w-none",children:f.jsx(Q0,{remarkPlugins:[eS,CS],rehypePlugins:[[TS,hD]],children:y.content})}):f.jsx("p",{className:"text-muted italic",children:"No content"})}):Qi?f.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:f.jsx(hy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)})}):an?f.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[f.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[f.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>Z("text"),className:`px-2 py-0.5 text-[11px] rounded ${L==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),f.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>Z("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${L==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),f.jsx("div",{className:"flex-1 min-h-0",children:L==="cuts"?f.jsx(hy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Ve(ee=>ee+1),focusRequest:he,onFocusHandled:()=>ye(null)}):Rr})]}):Rr,f.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?f.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:pa}):(y==null?void 0:y.status)==="published-not-indexed"?f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ar&&f.jsx("button",{onClick:async()=>{if(!(!e||!t||!y.txHash)){B(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:y.txHash,content:y.content,storylineId:y.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:y.txHash,storylineId:y.storylineId,contentCid:"",gasCost:""})}),$i())}catch{}B(!1)}},disabled:O,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:O?"Retrying...":`Retry Index${xn?` (${xn})`:""}`}),lr&&f.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. - -Retry Publish creates a NEW on-chain transaction and a SECOND, permanent chapter on PlotLink (PlotLink content is immutable). Only do this if the chapter never appeared after indexing. - -Create a new on-chain chapter anyway?`)||s==null||s(e,t,R,C,te)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),f.jsx("p",{className:"text-muted text-xs",children:ar?lr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":lr?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),y.indexError&&f.jsx("p",{className:"text-error text-xs",children:y.indexError})]}):(y==null?void 0:y.status)==="published"?f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:"text-green-700",children:"Published"}),y.storylineId&&f.jsx("a",{href:(()=>{var Ne;const ee=`https://plotlink.xyz/story/${y.storylineId}`;if(!lr)return ee;const Se=y.plotIndex!=null&&y.plotIndex>0?y.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ee}/${Se}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),y.txHash&&f.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Zi&&o&&y.storylineId&&(!y.authorAddress||y.authorAddress.toLowerCase()===o.toLowerCase())&&f.jsx("button",{onClick:()=>St(ee=>!ee),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ci?"Close Edit":"Edit Story"})]}),ci&&Zi&&y.storylineId&&f.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),xa(Mt),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ge(null),me(null),ct(null),we("unknown"),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:ts,className:"text-xs","data-testid":"cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("select",{value:fi,onChange:ee=>ne(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:nl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))}),f.jsx("select",{value:_e,onChange:ee=>Pe(ee.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))})]}),f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:Fe,onChange:ee=>Qe(ee.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:Ar,disabled:He||!ht,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:He?"Saving...":ht?"Save Changes":"Loading..."}),ki&&f.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),pi&&f.jsx("span",{className:"text-error text-xs",children:pi})]})]})]}):f.jsxs("div",{className:"flex flex-col gap-2",children:[Qi&&je&&je.total>0&&f.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[f.jsxs("span",{children:["Cuts: ",f.jsx("span",{className:"text-foreground font-medium",children:je.total})]}),f.jsxs("span",{children:["Clean: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withClean,"/",je.needClean]})]}),f.jsxs("span",{children:["Lettered: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.withText,"/",je.needClean]})]}),f.jsxs("span",{children:["Uploaded: ",f.jsxs("span",{className:"text-foreground font-medium",children:[je.uploaded,"/",je.total]})]}),x&&f.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),an&&ei&&f.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ei.total," planned",ei.total>0&&f.jsxs(f.Fragment,{children:[" ","· ",ei.withClean," clean"," ","· ",ei.withText," lettered"," ","· ",ei.exported," exported"," ","· ",ei.uploaded," uploaded"]})]}),(an||Qi)&&pa&&f.jsxs("div",{className:`${Io} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:fa===0?"Not started":"Next step"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:an?"Genesis (Episode 1)":"Future episode"})]}),f.jsx("span",{className:"text-xs text-muted",children:pa})]}),lr&&!Qi&&D==="preview"&&f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:Rt,onChange:ee=>_t(ee.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Rt&&f.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[f.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var ee;return(ee=Tn.current)==null?void 0:ee.click()},onDragOver:ee=>{ee.preventDefault(),ee.stopPropagation()},onDrop:ee=>{var Ne;ee.preventDefault(),ee.stopPropagation();const Se=(Ne=ee.dataTransfer.files)==null?void 0:Ne[0];Se&&gn(Se)},children:[f.jsx("input",{ref:Tn,type:"file",accept:"image/webp,image/jpeg",onChange:dl,className:"hidden"}),f.jsx("span",{className:"text-xs text-muted",children:Je?"Uploading...":"Drop image here or click to browse"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),at&&f.jsx("span",{className:"text-error text-xs",children:at}),Xe.map((ee,Se)=>f.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[f.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),f.jsxs("div",{className:"flex items-center gap-1.5",children:[f.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ee.url,")"]}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ee.url})`),gi(Se),setTimeout(()=>gi(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:qt===Se?"Copied!":"Copy"})]})]},ee.cid))]})]}),Zi&&c!=="cartoon"&&!(D==="edit"&&L==="cuts")&&f.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[f.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image ",f.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),xa(!1),f.jsxs("div",{className:"flex items-start gap-3",children:[Te&&f.jsxs("div",{className:"relative",children:[f.jsx("img",{src:Te,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsx("button",{onClick:()=>{ze.current=!0,st(null),ct(null),we("unknown"),ge(null),me(ee=>(ee&&URL.revokeObjectURL(ee),null)),Gt.current&&(Gt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("input",{ref:Gt,type:"file",accept:"image/webp,image/jpeg",onChange:ts,className:"text-xs","data-testid":"prepublish-cover-input"}),f.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),f.jsx("input",{ref:mn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Zt,className:"hidden","data-testid":"prepublish-cover-import-input"}),f.jsx("button",{type:"button",onClick:()=>{var ee;return(ee=mn.current)==null?void 0:ee.click()},disabled:de,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:de?"Importing…":"Import generated image (PNG ok)"}),H&&f.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),We&&f.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",We," — pick a file to override."]}),nt&&f.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[nt," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&ae==="none"&&!H&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create ",f.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),pi&&f.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:pi})]})]})]}),!da&&Wu(),!da&&_a(),!da&&f.jsxs("div",{className:"flex items-center gap-2",children:[Zi&&c!=="cartoon"&&f.jsxs(f.Fragment,{children:[f.jsxs("select",{value:R,"data-testid":"publish-genre-select",onChange:ee=>{Y(ee.target.value),ee.target.value&&Yt({genre:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${R?"border-border":"border-amber-500"}`,children:[!R&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),nl.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]}),f.jsxs("select",{value:C,"data-testid":"publish-language-select",onChange:ee=>{se(ee.target.value),ee.target.value&&Yt({language:ee.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${C?"border-border":"border-amber-500"}`,children:[!C&&f.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),Xr.map(ee=>f.jsx("option",{value:ee,children:ee},ee))]})]}),f.jsx("button",{onClick:async()=>{if(!e||!t)return;if(or.count>0){const Se=`This plot contains ${or.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. - -Please verify illustrations appear correctly in Preview before continuing. - -Publish now?`;if(!window.confirm(Se))return}const ee=Zi?H:null;ee?await(s==null?void 0:s(e,t,R,C,te,ee))&&(ze.current=!0,st(null),ct(null),we("unknown"),ge(null),me(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Gt.current&&(Gt.current.value="")):s==null||s(e,t,R,C,te)},disabled:!!a||is||pl||Po||Zi&&(!R||!C)||Qi&&$!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Zi&&c==="cartoon"&&(!R||!C)&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Zi&&c!=="cartoon"&&!R&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Zi&&c!=="cartoon"&&R&&!C&&f.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),is&&f.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Qi&&$==="error"&&f.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Qi&&$==="planning"&&f.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Qi&&$==="awaiting-upload"&&f.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",be," of ",Ee," still need an uploaded image"]})]}),da&&f.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),or.warnings.length>0&&f.jsx("div",{className:"flex flex-col gap-0.5",children:or.warnings.map((ee,Se)=>f.jsx("span",{className:"text-amber-600 text-xs",children:ee},Se))}),Zi&&c!=="cartoon"&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[f.jsx("input",{type:"checkbox",checked:te,onChange:ee=>{oe(ee.target.checked),Yt({isNsfw:ee.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),te&&f.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function gD(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image - it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function WS(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(d=>!d.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function xD({progress:e,onOpenStoryInfo:t}){return f.jsx("div",{className:"m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm","data-testid":"story-info-cta",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"Story info"}),f.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"story-info-next-action",children:[f.jsx("span",{className:"font-semibold",children:"Next: "}),f.jsx("span",{children:gD(e)})]})]}),f.jsx("button",{type:"button",onClick:t,disabled:!t,className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50","data-testid":"story-info-next-action-btn",children:"Next Action"})]})})}function GS({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return WS(e)==="story-info"?f.jsx(xD,{progress:e,onOpenStoryInfo:i}):f.jsx(xm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function _D({storyName:e,authFetch:t,refreshKey:i=0,onCoachAction:s,onOpenStoryInfo:a}){const[o,c]=w.useState(void 0),h=JSON.stringify([e,i]),[p,d]=w.useState(null);return p!==h&&(c(void 0),d(h)),w.useEffect(()=>{let _=!1;return t(`/api/stories/${e}/progress`).then(x=>x.ok?x.json():null).then(x=>{_||c(bD(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?f.jsx(GS,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):f.jsx(xm,{coach:null,showEmptyState:!0,onAction:s})}function bD(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function vD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,refreshKey:a=0}){const[o,c]=w.useState(null),[h,p]=w.useState(!0);return w.useEffect(()=>{let d=!1;return(async()=>{p(!0);try{const x=await t(`/api/stories/${e}/progress`),b=x.ok?await x.json():null;d||(c(b),p(!1))}catch{d||(c(null),p(!1))}})(),()=>{d=!0}},[e,t,a]),h?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!o||!o.metadata||!Array.isArray(o.episodes)?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):o.contentType==="cartoon"?f.jsx(ND,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):f.jsx(AD,{progress:o,storyName:e,onOpenFile:i})}function uu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return f.jsxs("span",{className:"text-[11px]",children:[f.jsxs("span",{className:"text-muted",children:[e,": "]}),f.jsx("span",{className:`font-medium ${s}`,children:t})]})}function YS({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return f.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),f.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),f.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[f.jsx(uu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),f.jsx(uu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&f.jsx(uu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&f.jsx(uu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const KS={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Mu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},VS={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},yD={done:"✓",current:"◓",todo:"○"},SD={done:"text-green-700",current:"text-accent",todo:"text-muted"};function XS({item:e}){return f.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[f.jsx("span",{className:`${SD[e.status]} flex-shrink-0`,"aria-hidden":!0,children:yD[e.status]}),f.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&f.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function py({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[i]}`,"aria-hidden":!0,children:KS[i]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&f.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[i]} flex-shrink-0`,children:VS[i]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?f.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:c}):c,f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>f.jsx(XS,{item:h},p))})]})}function wD(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function CD(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(kD(a));return s}function kD(e){return{label:e.label,status:e.status,detail:e.detail}}const ED={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function ND({progress:e,storyName:t,onOpenFile:i,onOpenStoryInfo:s}){const a=e.metadata,o=e.setup.hasStructure,c=e.cover==="present",p=!a.title||!a.language||!a.genre||!c,d=WS(e),_=f.jsx(GS,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,D)=>{E!=="view-progress"&&D&&i(t,D)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=d==="story-info"?"current":p?"needs-action":"done",v=o?"done":d==="whitepaper"?"current":"not-started",y=e.episodes.find(E=>E.kind==="genesis")??null,N=e.episodes.filter(E=>E.kind==="plot");let A=0;return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(YS,{progress:e}),f.jsx("div",{className:"border-b border-border","data-testid":"persistent-next-action",children:_}),f.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),f.jsx(py,{index:++A,title:"Define Story Info",status:b,items:x}),f.jsx(py,{index:++A,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),y?f.jsx(Bf,{index:++A,ep:y,isActive:d===y.file,storyName:t,onOpenFile:i}):f.jsx(Bf,{index:++A,ep:ED,isActive:d==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),N.map(E=>f.jsx(Bf,{index:++A,ep:E,isActive:d===E.file,storyName:t,onOpenFile:i},E.file)),f.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),f.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&f.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Bf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=wD(t,i),p=CD(t,o),d=t.title?`${t.label} · ${t.title}`:t.label,_=f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:`flex-shrink-0 ${Mu[h]}`,"aria-hidden":!0,children:KS[h]}),f.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",d]}),f.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${Mu[h]} flex-shrink-0`,children:VS[h]})]});return f.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?f.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):f.jsx("div",{"data-state":t.state,children:_}),f.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>f.jsx(XS,{item:x},b))})]})}const TD={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},my={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},jD={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function AD({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return f.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[f.jsx(YS,{progress:e}),e.nextAction&&f.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),f.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&f.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[f.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),f.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),f.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[f.jsx(gy,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),f.jsx(gy,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),f.jsxs("div",{className:"px-4 py-2",children:[f.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?f.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):f.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>f.jsx("li",{children:f.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[f.jsx("span",{className:`mt-0.5 ${my[o.state]}`,"aria-hidden":!0,children:TD[o.state]}),f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),f.jsx("span",{className:`ml-auto text-[10px] font-medium ${my[o.state]}`,children:jD[o.state]})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),f.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[f.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&f.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function gy({done:e,label:t,onClick:i}){const s=f.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[f.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),f.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?f.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):f.jsx("div",{children:s})}const RD=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function MD({storyTitle:e,active:t,onSelect:i}){return f.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[f.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[f.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),f.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),f.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:RD.map(s=>{const a=s.key===t;return f.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function DD({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[d,_]=w.useState(""),[x,b]=w.useState(""),[v,y]=w.useState(""),[N,A]=w.useState(!1),[E,D]=w.useState("cartoon"),[P,J]=w.useState("unknown"),[q,L]=w.useState(!1),[Z,he]=w.useState(!1),[ye,U]=w.useState(null),[re,W]=w.useState(!1),[G,X]=w.useState(null),[I,j]=w.useState(!1),O=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),he(!1),U(null),(async()=>{try{const[se,te]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!se.ok){C||(c(!0),a(!1));return}const oe=await se.json(),$=te.ok?await te.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(bu(oe.genre)??""),y(oe.language&&Xr.find(ue=>ue.toLowerCase()===oe.language.toLowerCase())||""),A(!!oe.isNsfw),D(oe.contentType==="fiction"?"fiction":"cartoon"),J(($==null?void 0:$.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const B=w.useCallback(async()=>{L(!0),he(!1),U(null);const C={title:h.trim(),description:d.trim(),genre:x,language:v,isNsfw:N};try{const se=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(se.ok)he(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const te=await se.json().catch(()=>({}));U(te.error||"Could not save story info.")}}catch{U("Could not save story info.")}L(!1)},[e,t,h,d,x,v,N,i]),xe=w.useCallback(async C=>{var te;const se=(te=C.target.files)==null?void 0:te[0];if(O.current&&(O.current.value=""),!!se){W(!0),U(null);try{let oe;try{oe=await qu(se)}catch(Ee){U(Ee instanceof Error?Ee.message:"Could not import image");return}const $=oe.type==="image/jpeg"?"jpg":"webp",ue=new File([oe],`cover.${$}`,{type:oe.type}),be=new FormData;be.append("file",ue);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:be});if(!De.ok){const Ee=await De.json().catch(()=>({}));U(Ee.error||"Cover import failed.");return}J("present"),X(Ee=>(Ee&&URL.revokeObjectURL(Ee),URL.createObjectURL(ue)))}catch{U("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var se;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(se=navigator.clipboard)==null||se.writeText(C).then(()=>{j(!0)}).catch(()=>{})},[h,e]);if(s)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const R=P==="present"?"Cover set":P==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",Y=P==="present"?"text-green-700":P==="invalid"?"text-amber-700":"text-muted";return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),f.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),f.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),he(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"flex flex-col gap-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),f.jsx("textarea",{value:d,onChange:C=>{_(C.target.value),he(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),f.jsxs("div",{className:"flex flex-wrap gap-4",children:[f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),f.jsxs("select",{value:x,onChange:C=>{b(C.target.value),he(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),nl.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),f.jsxs("select",{value:v,onChange:C=>{y(C.target.value),he(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"Needs metadata"}),Xr.map(C=>f.jsx("option",{value:C,children:C},C))]})]}),f.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),f.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),f.jsxs("div",{className:"flex items-start gap-3",children:[G&&f.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsx("span",{className:`text-[11px] font-medium ${Y}`,"data-testid":"story-info-cover-status",children:R}),f.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{type:"button",onClick:()=>{var C;return(C=O.current)==null?void 0:C.click()},disabled:re,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:re?"Importing…":"Import cover"}),f.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:I?"Copied!":"Ask agent for cover prompt"})]}),f.jsx("input",{ref:O,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),f.jsxs("label",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"checkbox",checked:N,onChange:C=>{A(C.target.checked),he(!1)},"data-testid":"story-info-nsfw"}),f.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{type:"button",onClick:B,disabled:q,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:q?"Saving…":"Save Story Info"}),Z&&f.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&f.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function BD({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const d=await t(`/api/stories/${e}/progress`),_=d.ok?await d.json():null;h||(a(Array.isArray(_==null?void 0:_.episodes)?_.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?f.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):f.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>f.jsx("li",{children:f.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:f.jsxs("span",{className:"min-w-0 flex-1",children:[f.jsxs("span",{className:"flex items-center gap-1.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&f.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),f.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),f.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function LD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:d=0}){var pt,Ge;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[y,N]=w.useState(!1),[A,E]=w.useState(null),[D,P]=w.useState(null),[J,q]=w.useState(null),[L,Z]=w.useState(null),[he,ye]=w.useState(null),U=async()=>{try{const Ae=await t(`/api/stories/${e}/cover-asset`),Ve=Ae.ok?await Ae.json():null;if(!(Ve!=null&&Ve.found)||!Ve.valid||!Ve.path)return null;const At=await t(`/api/stories/${e}/asset/${String(Ve.path).replace(/^assets\//,"")}`);if(!At.ok)return null;const Ot=await At.blob();return new File([Ot],String(Ve.path).split("/").pop()||"cover.webp",{type:Ve.type||Ot.type})}catch{return null}};w.useEffect(()=>{let Ae=!1;return(async()=>{v(!0),N(!1);try{const At=await t(`/api/stories/${e}/progress`),Ot=At.ok?await At.json():null;if(Ae)return;!Ot||!Array.isArray(Ot.episodes)?(N(!0),x(null)):x(Ot),v(!1)}catch{Ae||(N(!0),x(null),v(!1))}})(),()=>{Ae=!0}},[e,t,d]);const re=((Ge=(pt=_==null?void 0:_.episodes)==null?void 0:pt.find(Ae=>!Ae.published))==null?void 0:Ge.file)??null,W=re==="genesis.md",G=JSON.stringify([re??"",d]),[X,I]=w.useState(null);if(X!==G&&(I(G),P(null),q(null),Z(null),ye(null)),w.useEffect(()=>{if(!re)return;let Ae=!1;const Ve=re.replace(/\.md$/,"");return(async()=>{var At;try{const Ot=[t(`/api/stories/${e}/${re}`),t(`/api/stories/${e}/cuts/${Ve}`)];W&&Ot.push(t(`/api/stories/${e}/structure.md`));const[ci,St,fi]=await Promise.all(Ot);if(Ae)return;if(P(ci.ok?(await ci.json()).content??"":""),St.ok){const ne=await St.json();if(Ae)return;q(Array.isArray(ne.cuts)?ne.cuts:[]),Z(typeof ne.title=="string"?ne.title:null)}else q(null),Z(null);ye(W&&fi&&fi.ok?((At=await fi.json())==null?void 0:At.content)??null:null)}catch{Ae||(P(""),q(null),Z(null),ye(null))}})(),()=>{Ae=!0}},[re,W,e,t,d]),b)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(y||!_)return f.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const j=_.episodes.find(Ae=>!Ae.published);if(!j)return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),f.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const O=j.cuts,B=_.cover==="present",xe=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:O&&O.total>0?"done":"todo",detail:O?`${O.total} cut${O.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:O&&O.needClean>0&&O.withClean===O.needClean?"done":"todo",detail:O?`${O.withClean} / ${O.needClean}`:null},{label:"Cuts lettered",status:O&&O.needClean>0&&O.withText===O.needClean?"done":"todo",detail:O?`${O.withText} / ${O.needClean}`:null},{label:"Final images exported",status:O&&O.total>0&&O.exported===O.total?"done":"todo",detail:O?`${O.exported} / ${O.total}`:null},{label:"Final images uploaded",status:O&&O.total>0&&O.uploaded===O.total?"done":"todo",detail:O?`${O.uploaded} / ${O.total}`:null},{label:"Cover image",status:B?"done":"todo",detail:B?null:"recommended before publishing"},{label:"Publish to PlotLink",status:j.published?"done":"todo"}],T=j.state==="ready",R=j.state==="blocked",Y=j.file==="genesis.md",C=!Y||!!c&&!!h,se=!!o&&o===j.file,te=D!==null,oe=te?bm({fileName:j.file,fileContent:D??"",storySlug:e,structureContent:he,contentType:"cartoon",episodeTitle:L}):null,$=!!oe&&jo(oe,j.file),ue=!Y&&te&&!_m({fileContent:D??"",episodeTitle:L}),be=$||ue,De=Y&&te?mm(D??""):null,Ee=!!De&&De.blockers.length>0,Be=!Y&&te&&J!==null?PS(D??"",J):null,je=Be&&Be.stage==="error"?Be.issues:[],Ce=T&&C&&(te&&(Y||J!==null))&&!be&&!Ee&&!se&&!!a,tt=async()=>{if(!(!Ce||!a)){E(null);try{const Ae=Y?await U():null;await a(e,j.file,c??"",h??"",!!p,Ae)}catch{E("Publish could not be started. Please try again.")}}};return f.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[f.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",j.label]}),f.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),f.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Ae,Ve)=>f.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Ae.status,children:[f.jsx("span",{className:`flex-shrink-0 ${Ae.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Ae.status==="done"?"✓":"○"}),f.jsx("span",{className:Ae.status==="done"?"text-foreground":"text-muted",children:Ae.label}),Ae.detail&&f.jsxs("span",{className:"text-muted",children:["· ",Ae.detail]})]},Ve))}),oe&&f.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":$?"true":"false","data-blocked":be?"true":"false",children:[f.jsxs("span",{className:"text-[11px] text-foreground",children:[f.jsxs("span",{className:"font-medium",children:[Y?"Story title":"Episode title",":"]})," ",f.jsx("span",{className:be?"text-error font-medium":"text-foreground",children:oe})]}),$?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Y?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):ue?f.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",oe,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),De&&f.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":Ee?"true":"false",children:[f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),f.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),De.blockers.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Ae},`b-${Ve}`)),De.warnings.map((Ae,Ve)=>f.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Ae},`w-${Ve}`))]}),je.length>0&&f.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),f.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),IS(je).map(Ae=>f.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Ae.key}`,children:f.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Ae.title})},Ae.key)),f.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),f.jsx("ul",{className:"mt-1 ml-3 list-disc",children:je.map((Ae,Ve)=>f.jsx("li",{className:"font-mono break-words",children:Ae},Ve))})]})]}),f.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!B&&f.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),Y&&!C&&f.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&f.jsxs("button",{onClick:()=>i(e,j.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",j.label," to finish ",R?"and fix issues":"(letter / export / upload)"]}),f.jsx("button",{onClick:tt,disabled:!Ce,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:Ce?void 0:"Finish the remaining steps above first",children:se?"Publishing…":`Publish ${j.label} to PlotLink`}),T?C?be||Ee?f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Ee?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:f.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):f.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:R?`Not publishable yet — ${j.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${j.summary.toLowerCase()}.`}),A&&f.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:A})]}),f.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[f.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),f.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[f.jsxs("p",{children:["Episode file: ",f.jsx("span",{className:"font-mono",children:j.file})]}),f.jsxs("p",{children:["State: ",j.state," — ",j.summary]}),f.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function OD(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function zD(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?jo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=OD(i,s);return a?jo(a,t)||Lp(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function PD(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const ZS="plotlink-panel-ratio",ID=.6,xy=300,Lf=224,Of=6;function HD(){try{const e=localStorage.getItem(ZS);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return ID}function _y(e,t){if(t<=0)return e;const i=xy/t,s=1-xy/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function UD({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,d]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[y,N]=w.useState(null),[A,E]=w.useState(null),[D,P]=w.useState(HD),[J,q]=w.useState([]),[L,Z]=w.useState(!1),[he,ye]=w.useState(""),[U,re]=w.useState(""),[W,G]=w.useState(""),[X,I]=w.useState("English"),[j,O]=w.useState("normal"),[B,xe]=w.useState("claude"),[T,R]=w.useState(null),[Y,C]=w.useState(!1),[se,te]=w.useState({}),[oe,$]=w.useState({}),[ue,be]=w.useState(new Set),[De,Ee]=w.useState(new Set),[Be,je]=w.useState({}),[Ze,Ce]=w.useState({}),[tt,pt]=w.useState({}),[Ge,Ae]=w.useState({}),[Ve,At]=w.useState({}),[Ot,ci]=w.useState({}),St=w.useRef(new Map),fi=w.useRef(new Map),ne=w.useRef(new Map),_e=w.useRef(new Map),Pe=w.useRef(new Set),Fe=w.useRef(null),Qe=w.useRef(null),H=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(ae=>ae.ok?ae.json():null).then(ae=>{ae!=null&&ae.address&&E(ae.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&R(ae)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(ZS,String(D))}catch{}},[D]),w.useEffect(()=>{const ae=()=>{if(!Qe.current)return;const we=Qe.current.getBoundingClientRect().width-Lf-Of;P(ze=>_y(ze,we))};return window.addEventListener("resize",ae),ae(),()=>window.removeEventListener("resize",ae)},[]);const ge=w.useCallback(()=>{ye(""),re(""),G(""),O("normal"),xe("claude"),Z(!0)},[]),Te=w.useCallback(async(ae,we,ze,Rt)=>{const _t=he.trim();if(!_t)return;const Je=ae==="cartoon"?"codex":Rt;try{const ut=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:_t,description:U.trim()||void 0,language:we,genre:W||void 0,contentType:ae,agentMode:ze,agentProvider:Je})});if(!ut.ok)return;const at=await ut.json();Z(!1),je(wt=>({...wt,[at.name]:ae})),Ce(wt=>({...wt,[at.name]:we})),W&&pt(wt=>({...wt,[at.name]:W})),$(wt=>({...wt,[at.name]:Je})),ze==="bypass"&&te(wt=>({...wt,[at.name]:!0})),s(at.name),o(null)}catch{}},[t,he,U,W]);w.useEffect(()=>{if(J.length===0)return;const ae=setInterval(async()=>{try{const we=await t("/api/stories");if(!we.ok)return;const ze=await we.json(),Rt=new Set(ze.stories.filter(_t=>_t.name!=="_example").map(_t=>_t.name));for(const _t of Rt)if(!Pe.current.has(_t)&&J.length>0){const Je=J[0],ut=St.current.get(Je)||"fiction",at=fi.current.get(Je)||"English",wt=ne.current.get(Je)||"normal",Xe=_e.current.get(Je)||"claude";let zt=!1;Fe.current&&(zt=await Fe.current(Je,_t,{contentType:ut,language:at,agentMode:wt,agentProvider:Xe}).catch(()=>!1)),zt&&(q(qt=>qt.slice(1)),St.current.delete(Je),fi.current.delete(Je),ne.current.delete(Je),_e.current.delete(Je),wt==="bypass"&&te(qt=>{const gi={...qt,[_t]:!0};return delete gi[Je],gi}),$(qt=>{const gi={...qt,[_t]:Xe};return delete gi[Je],gi}),t(`/api/stories/${_t}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:ut,language:at,agentMode:wt,agentProvider:Xe})}).catch(()=>{})),s(_t),o(null)}Pe.current=Rt}catch{}},3e3);return()=>clearInterval(ae)},[t,J]),w.useEffect(()=>{t("/api/stories").then(ae=>{if(ae.ok)return ae.json()}).then(ae=>{ae!=null&&ae.stories&&(Pe.current=new Set(ae.stories.filter(we=>we.name!=="_example").map(we=>we.name)))}).catch(()=>{})},[t]);const me=w.useCallback((ae,we)=>{s(ae),o(we),h(null)},[]),He=w.useRef(null),Le=w.useCallback(async ae=>{var we,ze,Rt,_t;He.current=ae,s(ae),o(null),h(null);try{const Je=await t(`/api/stories/${ae}`);if(Je.ok&&He.current===ae){const ut=await Je.json();if(ut.contentType==="cartoon")return;const at=ut.files||[],Xe=((we=at.map(zt=>{var qt;return{file:zt.file,num:(qt=zt.file.match(/^plot-(\d+)\.md$/))==null?void 0:qt[1]}}).filter(zt=>zt.num!=null).sort((zt,qt)=>parseInt(qt.num)-parseInt(zt.num))[0])==null?void 0:we.file)??((ze=at.find(zt=>zt.file==="genesis.md"))==null?void 0:ze.file)??((Rt=at.find(zt=>zt.file==="structure.md"))==null?void 0:Rt.file)??((_t=at[0])==null?void 0:_t.file);Xe&&He.current===ae&&o(Xe)}}catch{}},[t]),ht=w.useCallback(ae=>{ae.preventDefault(),H.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const we=Rt=>{if(!H.current||!Qe.current)return;const _t=Qe.current.getBoundingClientRect(),Je=_t.width-Lf-Of,ut=Rt.clientX-_t.left-Lf;P(_y(ut/Je,Je))},ze=()=>{H.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",we),window.removeEventListener("mouseup",ze)};window.addEventListener("mousemove",we),window.addEventListener("mouseup",ze)},[]),it=w.useCallback(async(ae,we,ze,Rt,_t,Je)=>{var Xe;d(we),v("Reading file..."),N(null);let ut=!1,at=null,wt=!1;try{const zt=await t(`/api/stories/${ae}/${we}`);if(!zt.ok)throw new Error("Failed to read file");const qt=await zt.json(),gi=Be[ae];let Tn=null,mr=null;if(we==="genesis.md")try{const Yt=await t(`/api/stories/${ae}/structure.md`);Yt.ok&&(Tn=(await Yt.json()).content??null)}catch{}else if(gi==="cartoon"&&we.match(/^plot-\d+\.md$/))try{const Yt=await t(`/api/stories/${ae}/cuts/${we.replace(/\.md$/,"")}`);Yt.ok&&(mr=(await Yt.json()).title??null)}catch{}const $i=bm({fileName:we,fileContent:qt.content,storySlug:ae,structureContent:Tn,contentType:gi,episodeTitle:mr});if(gi==="cartoon"&&jo($i,we))return v(we==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{d(null),v("")},6e3),!1;if(gi==="cartoon"&&we.match(/^plot-\d+\.md$/)&&!_m({fileContent:qt.content,episodeTitle:mr}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{d(null),v("")},6e3),!1;if(gi==="cartoon"&&we==="genesis.md"){const Yt=mm(qt.content).blockers;if(Yt.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Yt[0]}`),setTimeout(()=>{d(null),v("")},6e3),!1}let ei;if(we.match(/^plot-\d+\.md$/)){if(lD(qt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{d(null),v("")},6e3);return}try{const Yt=await t(`/api/stories/${ae}`);if(Yt.ok){const sn=(await Yt.json()).files.find(An=>An.file==="genesis.md"&&An.storylineId);ei=sn==null?void 0:sn.storylineId}}catch{}if(!ei)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{d(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Yt=await t("/api/publish/preflight");if(Yt.ok){const qn=await Yt.json();if(cD(qn))return N(uD(qn)),d(null),v(""),!1}}catch{}v("Publishing...");const jn=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:ae,fileName:we,title:$i,content:qt.content,genre:ze,language:Rt,isNsfw:_t,storylineId:ei,...fy(Be,ae,ei)?{contentType:fy(Be,ae,ei)}:{}})});if(!jn.ok){const Yt=await jn.json();throw new Error(Yt.error||"Publish failed")}const Fn=(Xe=jn.body)==null?void 0:Xe.getReader(),ti=new TextDecoder;if(Fn)for(;;){const{done:Yt,value:qn}=await Fn.read();if(Yt)break;const An=ti.decode(qn).split(` -`).filter(ts=>ts.startsWith("data: "));for(const ts of An)try{const Zt=JSON.parse(ts.slice(6));if(Zt.step&&v(Zt.message||Zt.step),Zt.step==="done"&&Zt.txHash){if(wt=!0,await t(`/api/stories/${ae}/${we}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Zt.txHash,storylineId:Zt.storylineId,plotIndex:Zt.plotIndex,contentCid:Zt.contentCid,gasCost:Zt.gasCost,indexError:Zt.indexError,authorAddress:A})}),x(gn=>gn+1),Je&&we==="genesis.md"&&Zt.storylineId){v("Uploading cover...");let gn=null;try{gn=await nD(t,Zt.storylineId,Je)}catch{}gn||(ut=!0)}if(gi==="cartoon"&&Zt.storylineId)try{const gn=we!=="genesis.md",dl=`storylineId=${Zt.storylineId}`+(gn&&Zt.plotIndex!=null?`&plotIndex=${Zt.plotIndex}`:""),Ar=await t(`/api/publish/public-title?${dl}`);if(Ar.ok){const ar=await Ar.json(),xn=gn?{plots:ar.plotTitle!=null?[{plotIndex:Zt.plotIndex,title:ar.plotTitle}]:[]}:{title:ar.storylineTitle},Xi=zD({fileName:we,detail:xn,plotIndex:Zt.plotIndex});Xi.ok||(at=PD(Xi))}}catch{}}}catch{}}at&&N(at),v(ut?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(zt){const qt=zt instanceof Error?zt.message:"Publish failed";v(`Error: ${qt}`)}finally{setTimeout(()=>{d(null),v("")},3e3)}return wt&&!ut},[t,Be,A]),Mt=w.useCallback(ae=>{ae.startsWith("_new_")&&(q(we=>we.filter(ze=>ze!==ae)),St.current.delete(ae),fi.current.delete(ae),ne.current.delete(ae),_e.current.delete(ae),te(we=>{if(!(ae in we))return we;const ze={...we};return delete ze[ae],ze}),$(we=>{if(!(ae in we))return we;const ze={...we};return delete ze[ae],ze}))},[]);w.useEffect(()=>{const ae=ze=>{be(new Set(ze.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Ee(new Set(ze.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const Rt={},_t={},Je={},ut={},at={},wt={};for(const Xe of ze)Rt[Xe.name]=Xe.contentType||"fiction",_t[Xe.name]=Xe.language,Je[Xe.name]=Xe.genre,ut[Xe.name]=Xe.isNsfw,at[Xe.name]=Xe.agentProvider,Xe.title&&(wt[Xe.name]=Xe.title);je(Rt),Ce(_t),pt(Je),Ae(ut),ci(at),At(wt)};t("/api/stories").then(ze=>ze.ok?ze.json():null).then(ze=>{ze!=null&&ze.stories&&ae(ze.stories)}).catch(()=>{});const we=setInterval(async()=>{try{const ze=await t("/api/stories");if(ze.ok){const Rt=await ze.json();ae(Rt.stories)}}catch{}},5e3);return()=>clearInterval(we)},[t]);const Dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",pi=!!T&&!Dt,kt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),ki=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const ae=i;if((await t(`/api/stories/${ae}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ci(ze=>({...ze,[ae]:"codex"})),$(ze=>({...ze,[ae]:"codex"}));try{const ze=await t("/api/stories");if(ze.ok){const Rt=await ze.json();if(Rt!=null&&Rt.stories){const _t={};for(const Je of Rt.stories)_t[Je.name]=Je.agentProvider;ci(_t)}}}catch{}}},[t,i]),mi=w.useCallback(ae=>{i===ae&&(s(null),o(null))},[i]),Gt=i?oe[i]??Ot[i]:void 0,mn=Mf(i,Be,St.current),de=oD(mn,Gt,i),Re=!!i&&mn==="cartoon",We=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",st=w.useCallback(ae=>{const we=i;if(we)switch(ae){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":me(we,"structure.md");break;case"genesis":me(we,"genesis.md");break;case"publish":h("publish");break}},[i,me]),nt=w.useCallback((ae,we)=>{const ze=i;if(ze)switch(ae){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":we&&me(ze,we);break}},[i,me]),ct=w.useCallback(ae=>{i&&(ae.genre!==void 0&&pt(we=>({...we,[i]:ae.genre||void 0})),ae.language!==void 0&&Ce(we=>({...we,[i]:ae.language||void 0})),ae.isNsfw!==void 0&&Ae(we=>({...we,[i]:ae.isNsfw})))},[i]);return f.jsxs("div",{ref:Qe,className:"h-[calc(100vh-3.5rem)] flex",children:[f.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:f.jsx(bC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:me,onNewStory:ge,untitledSessions:J})}),f.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${D} 0 0`},children:f.jsx(WE,{token:e,storyName:i,authFetch:t,onSelectStory:Le,onDestroySession:Mt,onArchiveStory:mi,confirmedStories:ue,renameRef:Fe,bypassStories:se,agentProviders:oe,readiness:T,contentType:Mf(i,Be,St.current),needsProviderRepair:de,onRepairProvider:ki})}),f.jsx("div",{onMouseDown:ht,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Of,cursor:"col-resize",background:"var(--border)"},children:f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),f.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),f.jsxs("div",{className:"min-w-0 flex flex-col",style:{flex:`${1-D} 0 0`},children:[Re&&i&&f.jsx(MD,{storyTitle:Ve[i]||i,active:We,onSelect:st}),Re&&i&&c!==null&&f.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:f.jsx(_D,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:nt,onOpenStoryInfo:()=>h("story-info")})}),Re&&c==="story-info"&&i?f.jsx(DD,{storyName:i,authFetch:t,onSaved:ct}):Re&&c==="episodes"&&i?f.jsx(BD,{storyName:i,authFetch:t,onOpenFile:me}):Re&&c==="publish"&&i?f.jsx(LD,{storyName:i,authFetch:t,onOpenFile:me,onOpenStoryInfo:()=>h("story-info"),onPublish:it,publishingFile:p,genre:tt[i],language:Ze[i],isNsfw:Ge[i],refreshKey:_}):i&&!a?f.jsx(vD,{storyName:i,authFetch:t,onOpenFile:me,onOpenStoryInfo:()=>h("story-info")}):f.jsx(mD,{storyName:i,fileName:a,authFetch:t,onPublish:it,publishingFile:p,walletAddress:A,contentType:Mf(i,Be,St.current)||"fiction",language:i?Ze[i]:void 0,genre:i?tt[i]:void 0,isNsfw:i?Ge[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:ae=>i&&me(i,ae),onViewPublish:()=>h("publish")}),b&&f.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),y&&f.jsxs("div",{className:"px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[f.jsx("span",{children:y}),f.jsx("button",{type:"button",onClick:()=>N(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),L&&f.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:f.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[f.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),f.jsxs("label",{className:"block space-y-1",children:[f.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",f.jsx("span",{className:"text-accent",children:"*"})]}),f.jsx("input",{type:"text",value:he,onChange:ae=>ye(ae.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),f.jsx("input",{type:"text",value:U,onChange:ae=>re(ae.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),f.jsxs("select",{value:W,onChange:ae=>G(ae.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[f.jsx("option",{value:"",children:"— Select later —"}),nl.map(ae=>f.jsx("option",{value:ae,children:ae},ae))]})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),f.jsx("select",{value:X,onChange:ae=>I(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:Xr.map(ae=>f.jsx("option",{value:ae,children:ae},ae))})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),f.jsxs("select",{value:j,onChange:ae=>O(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[f.jsx("option",{value:"normal",children:"Normal (approve each action)"}),f.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),j==="bypass"&&f.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),f.jsxs("label",{className:"block space-y-1",children:[f.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),f.jsxs("select",{value:B,onChange:ae=>xe(ae.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[f.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),f.jsx("option",{value:"codex",children:"🎨 Codex"})]}),f.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:B==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),f.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!he.trim()&&f.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),f.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[f.jsxs("button",{onClick:()=>Te("fiction",X,j,B),disabled:!he.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),f.jsxs("div",{className:"space-y-1",children:[f.jsxs("button",{onClick:()=>Te("cartoon",X,j,"codex"),disabled:pi||!he.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[f.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),f.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),f.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&f.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",f.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",f.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Su(T)&&f.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:zp}),T&&T.codex.installed&&!Su(T)&&T.codex.imageGeneration!=="enabled"&&f.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[f.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),f.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[f.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),f.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:kt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:Y?"Copied!":"Copy"})]})]})]})]}),f.jsx("button",{onClick:()=>Z(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function $D({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const d=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await d.json();if(!d.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(d){o(d instanceof Error?d.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),f.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[f.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),f.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&f.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),f.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"text-accent text-2xl",children:"✓"}),f.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),f.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function FD({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(d,_)=>fetch(d,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(d=>d.json()).then(d=>{d.version&&h(d.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function d(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(y=>y.name!=="_example").length)}}catch{}}d()},[e]),f.jsxs("div",{className:"flex h-screen flex-col",children:[f.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:f.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),f.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&f.jsxs("nav",{className:"flex items-center gap-4",children:[f.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),f.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),f.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),f.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),f.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&f.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),f.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),f.jsxs("div",{className:"text-center space-y-3",children:[f.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&f.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),f.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[f.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),f.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[f.jsxs("li",{children:["Open the ",f.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),f.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),f.jsx("li",{children:"Review the live preview as the agent creates files"}),f.jsxs("li",{children:["Click ",f.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),f.jsxs("li",{children:["Earn 5% royalties on every trade at ",f.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),f.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),f.jsx("div",{className:"text-center",children:f.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),f.jsx(Sy,{token:e})]}),i==="stories"&&f.jsx(UD,{token:e,authFetch:p}),i==="dashboard"&&f.jsx(gC,{token:e}),i==="wallet-setup"&&f.jsx($D,{token:e,onComplete:()=>s("home")}),i==="settings"&&f.jsx(pC,{token:e,onLogout:t})]})]})}function qD(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(d=>d.json()).then(d=>s(d.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(d=>{d.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async d=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),null):x.error||"Login failed"}catch{return"Cannot connect to server"}},h=async d=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:d})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),s(!0),null):x.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?f.jsx("div",{className:"flex h-screen items-center justify-center",children:f.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?f.jsx(FD,{token:e,onLogout:p}):f.jsx(dC,{onLogin:c}):f.jsx(fC,{onSetup:h})}hC.createRoot(document.getElementById("root")).render(f.jsx(nC.StrictMode,{children:f.jsx(qD,{})}));export{Dp as M,su as a,N3 as b,BM as c,j3 as d,ru as l,BS as s,U3 as t,VD as v}; diff --git a/app/web/dist/assets/index-Mt6kwRka.js b/app/web/dist/assets/index-Mt6kwRka.js new file mode 100644 index 0000000..213635a --- /dev/null +++ b/app/web/dist/assets/index-Mt6kwRka.js @@ -0,0 +1,143 @@ +(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 Du(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qd={exports:{}},to={};/** + * @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 X_;function iC(){if(X_)return to;X_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return to.Fragment=t,to.jsx=i,to.jsxs=i,to}var Z_;function nC(){return Z_||(Z_=1,qd.exports=iC()),qd.exports}var d=nC(),Wd={exports:{}},et={};/** + * @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 Q_;function rC(){if(Q_)return et;Q_=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(R){return R===null||typeof R!="object"?null:(R=b&&R[b]||R["@@iterator"],typeof R=="function"?R:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,j={};function E(R,V,C){this.props=R,this.context=V,this.refs=j,this.updater=C||y}E.prototype.isReactComponent={},E.prototype.setState=function(R,V){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,V,"setState")},E.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function z(){}z.prototype=E.prototype;function O(R,V,C){this.props=R,this.context=V,this.refs=j,this.updater=C||y}var W=O.prototype=new z;W.constructor=O,N(W,E.prototype),W.isPureReactComponent=!0;var q=Array.isArray;function D(){}var te={H:null,A:null,T:null,S:null},de=Object.prototype.hasOwnProperty;function _e(R,V,C){var K=C.ref;return{$$typeof:e,type:R,key:V,ref:K!==void 0?K:null,props:C}}function P(R,V){return _e(R.type,V,R.props)}function ae(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function G(R){var V={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(C){return V[C]})}var Y=/\/+/g;function Q(R,V){return typeof R=="object"&&R!==null&&R.key!=null?G(""+R.key):V.toString(36)}function I(R){switch(R.status){case"fulfilled":return R.value;case"rejected":throw R.reason;default:switch(typeof R.status=="string"?R.then(D,D):(R.status="pending",R.then(function(V){R.status==="pending"&&(R.status="fulfilled",R.value=V)},function(V){R.status==="pending"&&(R.status="rejected",R.reason=V)})),R.status){case"fulfilled":return R.value;case"rejected":throw R.reason}}throw R}function A(R,V,C,K,re){var ue=typeof R;(ue==="undefined"||ue==="boolean")&&(R=null);var $=!1;if(R===null)$=!0;else switch(ue){case"bigint":case"string":case"number":$=!0;break;case"object":switch(R.$$typeof){case e:case t:$=!0;break;case _:return $=R._init,A($(R._payload),V,C,K,re)}}if($)return re=re(R),$=K===""?"."+Q(R,0):K,q(re)?(C="",$!=null&&(C=$.replace(Y,"$&/")+"/"),A(re,V,C,"",function(Te){return Te})):re!=null&&(ae(re)&&(re=P(re,C+(re.key==null||R&&R.key===re.key?"":(""+re.key).replace(Y,"$&/")+"/")+$)),V.push(re)),1;$=0;var le=K===""?".":K+":";if(q(R))for(var be=0;be>>1,T=A[ge];if(0>>1;gea(C,U))Ka(re,C)?(A[ge]=re,A[K]=U,ge=K):(A[ge]=C,A[V]=U,ge=V);else if(Ka(re,U))A[ge]=re,A[K]=U,ge=K;else break e}}return B}function a(A,B){var U=A.sortIndex-B.sortIndex;return U!==0?U:A.id-B.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,y=!1,N=!1,j=!1,E=typeof setTimeout=="function"?setTimeout:null,z=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function W(A){for(var B=i(f);B!==null;){if(B.callback===null)s(f);else if(B.startTime<=A)s(f),B.sortIndex=B.expirationTime,t(p,B);else break;B=i(f)}}function q(A){if(N=!1,W(A),!y)if(i(p)!==null)y=!0,D||(D=!0,G());else{var B=i(f);B!==null&&I(q,B.startTime-A)}}var D=!1,te=-1,de=5,_e=-1;function P(){return j?!0:!(e.unstable_now()-_eA&&P());){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,W(A),B=!0;break t}x===i(p)&&s(p),W(A)}else s(p);x=i(p)}if(x!==null)B=!0;else{var R=i(f);R!==null&&I(q,R.startTime-A),B=!1}}break e}finally{x=null,b=U,v=!1}B=void 0}}finally{B?G():D=!1}}}var G;if(typeof O=="function")G=function(){O(ae)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,Q=Y.port2;Y.port1.onmessage=ae,G=function(){Q.postMessage(null)}}else G=function(){E(ae,0)};function I(A,B){te=E(function(){A(e.unstable_now())},B)}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=U,t(f,A),i(p)===null&&A===i(f)&&(N?(z(te),te=-1):N=!0,I(q,U-ge))):(A.sortIndex=T,t(p,A),y||v||(y=!0,D||(D=!0,G()))),A},e.unstable_shouldYield=P,e.unstable_wrapCallback=function(A){var B=b;return function(){var U=b;b=B;try{return A.apply(this,arguments)}finally{b=U}}}})(Kd)),Kd}var tb;function lC(){return tb||(tb=1,Yd.exports=aC()),Yd.exports}var Vd={exports:{}},tn={};/** + * @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 ib;function oC(){if(ib)return tn;ib=1;var e=Op();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(),Vd.exports=oC(),Vd.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 rb;function uC(){if(rb)return io;rb=1;var e=lC(),t=Op(),i=cC();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 K=R(null),re=R(null),ue=R(null),$=R(null);function le(n,r){switch(C(ue,r),C(re,n),C(K,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?b_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=b_(r),n=v_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}V(K),C(K,n)}function be(){V(K),V(re),V(ue)}function Te(n){n.memoizedState!==null&&C($,n);var r=K.current,l=v_(r,n.type);r!==l&&(C(re,n),C(K,l))}function Le(n){re.current===n&&(V(K),V(re)),$.current===n&&(V($),Zl._currentValue=U)}var ze,ye;function rt(n){if(ze===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);ze=r&&r[1]||"",ye=-1)":-1m||M[u]!==Z[m]){var ce=` +`+M[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{bt=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?rt(l):""}function vt(n,r){switch(n.tag){case 26:case 27:case 5:return rt(n.type);case 16:return rt("Lazy");case 13:return n.child!==r&&r!==null?rt("Suspense Fallback"):rt("Suspense");case 19:return rt("SuspenseList");case 0:case 15:return wt(n.type,!1);case 11:return wt(n.type.render,!1);case 1:return wt(n.type,!0);case 31:return rt("Activity");default:return""}}function Ve(n){try{var r="",l=null;do r+=vt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +Error generating stack: `+u.message+` +`+u.stack}}var Me=Object.prototype.hasOwnProperty,Je=e.unstable_scheduleCallback,It=e.unstable_cancelCallback,Ae=e.unstable_shouldYield,ii=e.unstable_requestPaint,Ct=e.unstable_now,pi=e.unstable_getCurrentPriorityLevel,ne=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,Be=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Ge=e.unstable_IdlePriority,Ot=e.log,Mt=e.unstable_setDisableYieldValue,ct=null,We=null;function Bt(n){if(typeof Ot=="function"&&Mt(n),We&&typeof We.setStrictMode=="function")try{We.setStrictMode(ct,n)}catch{}}var pt=Math.clz32?Math.clz32:ke,Mi=Math.log,H=Math.LN2;function ke(n){return n>>>=0,n===0?32:31-(Mi(n)/H|0)|0}var Pe=256,je=262144,Ie=4194304;function Xe(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 mt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,S=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Xe(u):(S&=k,S!==0?m=Xe(S):l||(l=k&~n,l!==0&&(m=Xe(l))))):(k=u&~g,k!==0?m=Xe(k):S!==0?m=Xe(S):l||(l=u&~n,l!==0&&(m=Xe(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 Qe(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function Tt(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 qt(){var n=Ie;return Ie<<=1,(Ie&62914560)===0&&(Ie=4194304),n}function li(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function oe(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Ee(n,r,l,u,m,g){var S=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,M=n.expirationTimes,Z=n.hiddenUpdates;for(l=S&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var da=/[\n"\\]/g;function Ei(n){return n.replace(da,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function fa(n,r,l,u,m,g,S,k){n.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?n.type=S:n.removeAttribute("type"),r!=null?S==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Qi(r)):n.value!==""+Qi(r)&&(n.value=""+Qi(r)):S!=="submit"&&S!=="reset"||n.removeAttribute("value"),r!=null?ma(n,S,Qi(r)):l!=null?ma(n,S,Qi(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=""+Qi(k):n.removeAttribute("name")}function pa(n,r,l,u,m,g,S,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){cr(n);return}l=l!=null?""+Qi(l):"",r=r!=null?""+Qi(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(n.name=S),cr(n)}function ma(n,r,l){r==="number"&&on(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Gn(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"),_i=!1;if(jt)try{var Rn={};Object.defineProperty(Rn,"passive",{get:function(){_i=!0}}),window.addEventListener("test",Rn,Rn),window.removeEventListener("test",Rn,Rn)}catch{_i=!1}var un=null,hr=null,Ls=null;function vm(){if(Ls)return Ls;var n,r=hr,l=r.length,u,m="value"in un?un.value:un.textContent,g=m.length;for(n=0;n=_l),Em=" ",Nm=!1;function Tm(n,r){switch(n){case"keyup":return C1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var ba=!1;function E1(n,r){switch(n){case"compositionend":return jm(r);case"keypress":return r.which!==32?null:(Nm=!0,Em);case"textInput":return n=r.data,n===Em&&Nm?null:n;default:return null}}function N1(n,r){if(ba)return n==="compositionend"||!Xu&&Tm(n,r)?(n=vm(),Ls=hr=un=null,ba=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=zm(l)}}function Im(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Im(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Hm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=on(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=on(n.document)}return r}function Ju(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var L1=jt&&"documentMode"in document&&11>=document.documentMode,va=null,eh=null,Sl=null,th=!1;function Um(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;th||va==null||va!==on(u)||(u=va,"selectionStart"in u&&Ju(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Sl&&yl(Sl,u)||(Sl=u,u=Dc(eh,"onSelect"),0>=S,m-=S,xr=1<<32-pt(r)+m|l<at?(St=Oe,Oe=null):St=Oe.sibling;var Rt=J(F,Oe,X[at],he);if(Rt===null){Oe===null&&(Oe=St);break}n&&Oe&&Rt.alternate===null&&r(F,Oe),L=g(Rt,L,at),At===null?He=Rt:At.sibling=Rt,At=Rt,Oe=St}if(at===X.length)return l(F,Oe),Et&&Dr(F,at),He;if(Oe===null){for(;atat?(St=Oe,Oe=null):St=Oe.sibling;var Cs=J(F,Oe,Rt.value,he);if(Cs===null){Oe===null&&(Oe=St);break}n&&Oe&&Cs.alternate===null&&r(F,Oe),L=g(Cs,L,at),At===null?He=Cs:At.sibling=Cs,At=Cs,Oe=St}if(Rt.done)return l(F,Oe),Et&&Dr(F,at),He;if(Oe===null){for(;!Rt.done;at++,Rt=X.next())Rt=fe(F,Rt.value,he),Rt!==null&&(L=g(Rt,L,at),At===null?He=Rt:At.sibling=Rt,At=Rt);return Et&&Dr(F,at),He}for(Oe=u(Oe);!Rt.done;at++,Rt=X.next())Rt=se(Oe,F,at,Rt.value,he),Rt!==null&&(n&&Rt.alternate!==null&&Oe.delete(Rt.key===null?at:Rt.key),L=g(Rt,L,at),At===null?He=Rt:At.sibling=Rt,At=Rt);return n&&Oe.forEach(function(tC){return r(F,tC)}),Et&&Dr(F,at),He}function $t(F,L,X,he){if(typeof X=="object"&&X!==null&&X.type===N&&X.key===null&&(X=X.props.children),typeof X=="object"&&X!==null){switch(X.$$typeof){case v:e:{for(var He=X.key;L!==null;){if(L.key===He){if(He=X.type,He===N){if(L.tag===7){l(F,L.sibling),he=m(L,X.props.children),he.return=F,F=he;break e}}else if(L.elementType===He||typeof He=="object"&&He!==null&&He.$$typeof===de&&Ws(He)===L.type){l(F,L.sibling),he=m(L,X.props),Tl(he,X),he.return=F,F=he;break e}l(F,L);break}else r(F,L);L=L.sibling}X.type===N?(he=Hs(X.props.children,F.mode,he,X.key),he.return=F,F=he):(he=Xo(X.type,X.key,X.props,null,F.mode,he),Tl(he,X),he.return=F,F=he)}return S(F);case y:e:{for(He=X.key;L!==null;){if(L.key===He)if(L.tag===4&&L.stateNode.containerInfo===X.containerInfo&&L.stateNode.implementation===X.implementation){l(F,L.sibling),he=m(L,X.children||[]),he.return=F,F=he;break e}else{l(F,L);break}else r(F,L);L=L.sibling}he=oh(X,F.mode,he),he.return=F,F=he}return S(F);case de:return X=Ws(X),$t(F,L,X,he)}if(I(X))return De(F,L,X,he);if(G(X)){if(He=G(X),typeof He!="function")throw Error(s(150));return X=He.call(X),qe(F,L,X,he)}if(typeof X.then=="function")return $t(F,L,nc(X),he);if(X.$$typeof===O)return $t(F,L,Jo(F,X),he);rc(F,X)}return typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint"?(X=""+X,L!==null&&L.tag===6?(l(F,L.sibling),he=m(L,X),he.return=F,F=he):(l(F,L),he=lh(X,F.mode,he),he.return=F,F=he),S(F)):l(F,L)}return function(F,L,X,he){try{Nl=0;var He=$t(F,L,X,he);return Ra=null,He}catch(Oe){if(Oe===Aa||Oe===tc)throw Oe;var At=Dn(29,Oe,null,F.mode);return At.lanes=he,At.return=F,At}finally{}}}var Ys=ug(!0),hg=ug(!1),ls=!1;function vh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function yh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function os(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function cs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Dt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=Vo(n),Km(n,null,l),r}return Ko(n,u,r,l),Vo(n)}function jl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Ye(n,l)}}function Sh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=S:g=g.next=S,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var wh=!1;function Al(){if(wh){var n=ja;if(n!==null)throw n}}function Rl(n,r,l,u){wh=!1;var m=n.updateQueue;ls=!1;var g=m.firstBaseUpdate,S=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var M=k,Z=M.next;M.next=null,S===null?g=Z:S.next=Z,S=M;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==S&&(k===null?ce.firstBaseUpdate=Z:k.next=Z,ce.lastBaseUpdate=M))}if(g!==null){var fe=m.baseState;S=0,ce=Z=M=null,k=g;do{var J=k.lane&-536870913,se=J!==k.lane;if(se?(yt&J)===J:(u&J)===J){J!==0&&J===Ta&&(wh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var De=n,qe=k;J=r;var $t=l;switch(qe.tag){case 1:if(De=qe.payload,typeof De=="function"){fe=De.call($t,fe,J);break e}fe=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=qe.payload,J=typeof De=="function"?De.call($t,fe,J):De,J==null)break e;fe=x({},fe,J);break e;case 2:ls=!0}}J=k.callback,J!==null&&(n.flags|=64,se&&(n.flags|=8192),se=m.callbacks,se===null?m.callbacks=[J]:se.push(J))}else se={lane:J,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(Z=ce=se,M=fe):ce=ce.next=se,S|=J;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;se=k,k=se.next,se.next=null,m.lastBaseUpdate=se,m.shared.pending=null}}while(!0);ce===null&&(M=fe),m.baseState=M,m.firstBaseUpdate=Z,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),ps|=S,n.lanes=S,n.memoizedState=fe}}function dg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function fg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var S=A.T,k={};A.T=k,$h(n,!1,r,l);try{var M=m(),Z=A.S;if(Z!==null&&Z(k,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var ce=q1(M,u);Bl(n,r,ce,Pn(n))}else Bl(n,r,u,Pn(n))}catch(fe){Bl(n,r,{then:function(){},status:"rejected",reason:fe},Pn())}finally{B.p=g,S!==null&&k.types!==null&&(S.types=k.types),A.T=S}}function X1(){}function Hh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Wg(n).queue;qg(n,m,r,U,l===null?X1:function(){return Gg(n),l(u)})}function Wg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:U,baseState:U,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:U},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:zr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Gg(n){var r=Wg(n);r.next===null&&(r=n.alternate.memoizedState),Bl(n,r.next.queue,{},Pn())}function Uh(){return Gi(Zl)}function Yg(){return gi().memoizedState}function Kg(){return gi().memoizedState}function Z1(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Pn();n=os(l);var u=cs(r,n,l);u!==null&&(Cn(u,r,l),jl(u,r,l)),r={cache:gh()},n.payload=r;return}r=r.return}}function Q1(n,r,l){var u=Pn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pc(n)?Xg(r,l):(l=sh(n,r,l,u),l!==null&&(Cn(l,n,u),Zg(l,r,u)))}function Vg(n,r,l){var u=Pn();Bl(n,r,l,u)}function Bl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(pc(n))Xg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var S=r.lastRenderedState,k=g(S,l);if(m.hasEagerState=!0,m.eagerState=k,Mn(k,S))return Ko(n,r,m,0),Wt===null&&Yo(),!1}catch{}finally{}if(l=sh(n,r,m,u),l!==null)return Cn(l,n,u),Zg(l,r,u),!0}return!1}function $h(n,r,l,u){if(u={lane:2,revertLane:vd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},pc(n)){if(r)throw Error(s(479))}else r=sh(n,l,u,2),r!==null&&Cn(r,n,2)}function pc(n){var r=n.alternate;return n===nt||r!==null&&r===nt}function Xg(n,r){Da=lc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function Zg(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Ye(n,l)}}var Ll={readContext:Gi,use:uc,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};Ll.useEffectEvent=ci;var Qg={readContext:Gi,use:uc,useCallback:function(n,r){return hn().memoizedState=[n,r===void 0?null:r],n},useContext:Gi,useEffect:Lg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,dc(4194308,4,Ig.bind(null,r,n),l)},useLayoutEffect:function(n,r){return dc(4194308,4,n,r)},useInsertionEffect:function(n,r){dc(4,2,n,r)},useMemo:function(n,r){var l=hn();r=r===void 0?null:r;var u=n();if(Ks){Bt(!0);try{n()}finally{Bt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=hn();if(l!==void 0){var m=l(r);if(Ks){Bt(!0);try{l(r)}finally{Bt(!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=Q1.bind(null,nt,n),[u.memoizedState,n]},useRef:function(n){var r=hn();return n={current:n},r.memoizedState=n},useState:function(n){n=Lh(n);var r=n.queue,l=Vg.bind(null,nt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Ph,useDeferredValue:function(n,r){var l=hn();return Ih(l,n,r)},useTransition:function(){var n=Lh(!1);return n=qg.bind(null,nt,n.queue,!0,!1),hn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=nt,m=hn();if(Et){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Wt===null)throw Error(s(349));(yt&127)!==0||bg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Lg(yg.bind(null,u,g,n),[n]),u.flags|=2048,La(9,{destroy:void 0},vg.bind(null,u,g,l,r),null),l},useId:function(){var n=hn(),r=Wt.identifierPrefix;if(Et){var l=_r,u=xr;l=(u&~(1<<32-pt(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=oc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}g[st]=r,g[it]=u;e:for(S=r.child;S!==null;){if(S.tag===5||S.tag===6)g.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===r)break e;for(;S.sibling===null;){if(S.return===null||S.return===r)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}r.stateNode=g;e:switch(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&&Ir(r)}}return Zt(r),id(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Ir(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=ue.current,Ea(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Wi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[st]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||x_(n.nodeValue,l)),n||ss(r,!0)}else n=Bc(n).createTextNode(u),n[st]=r,r.stateNode=n}return Zt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ea(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[st]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Ln(r),r):(Ln(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Zt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ea(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[st]=r}else Us(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=dh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Ln(r),r):(Ln(r),null)}return Ln(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),bc(r,r.updateQueue),Zt(r),null);case 4:return be(),n===null&&Cd(r.stateNode.containerInfo),Zt(r),null;case 10:return Lr(r.type),Zt(r),null;case 19:if(V(mi),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)zl(u,!1);else{if(ui!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=ac(n),g!==null){for(r.flags|=128,zl(u,!1),n=g.updateQueue,r.updateQueue=n,bc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Vm(l,n),l=l.sibling;return C(mi,mi.current&1|2),Et&&Dr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Cc&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304)}else{if(!m)if(n=ac(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,bc(r,n),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!Et)return Zt(r),null}else 2*Ct()-u.renderingStartTime>Cc&&l!==536870912&&(r.flags|=128,m=!0,zl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=Ct(),n.sibling=null,l=mi.current,C(mi,m?l&1|2:l&1),Et&&Dr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Ln(r),kh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&bc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&V(qs),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Lr(bi),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function nw(n,r){switch(uh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Lr(bi),be(),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));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Ln(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Us()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return V(mi),null;case 4:return be(),null;case 10:return Lr(r.type),null;case 22:case 23:return Ln(r),kh(),n!==null&&V(qs),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Lr(bi),null;case 25:return null;default:return null}}function Sx(n,r){switch(uh(r),r.tag){case 3:Lr(bi),be();break;case 26:case 27:case 5:Le(r);break;case 4:be();break;case 31:r.memoizedState!==null&&Ln(r);break;case 13:Ln(r);break;case 19:V(mi);break;case 10:Lr(r.type);break;case 22:case 23:Ln(r),kh(),n!==null&&V(qs);break;case 24:Lr(bi)}}function Pl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,S=l.inst;u=g(),S.destroy=u}l=l.next}while(l!==m)}}catch(k){Pt(r,r.return,k)}}function ds(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var S=u.inst,k=S.destroy;if(k!==void 0){S.destroy=void 0,m=r;var M=l,Z=k;try{Z()}catch(ce){Pt(m,M,ce)}}}u=u.next}while(u!==g)}}catch(ce){Pt(r,r.return,ce)}}function wx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{fg(r,l)}catch(u){Pt(n,n.return,u)}}}function Cx(n,r,l){l.props=Vs(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Pt(n,r,u)}}function Il(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Pt(n,r,m)}}function br(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 kx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Pt(n,n.return,m)}}function nd(n,r,l){try{var u=n.stateNode;kw(u,n.type,l,r),u[it]=r}catch(m){Pt(n,n.return,m)}}function Ex(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&bs(n.type)||n.tag===4}function rd(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Ex(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&bs(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function sd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=cn));else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(sd(n,r,l),n=n.sibling;n!==null;)sd(n,r,l),n=n.sibling}function vc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&bs(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(vc(n,r,l),n=n.sibling;n!==null;)vc(n,r,l),n=n.sibling}function Nx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Ki(r,u,l),r[st]=n,r[it]=l}catch(g){Pt(n,n.return,g)}}var Hr=!1,Si=!1,ad=!1,Tx=typeof WeakSet=="function"?WeakSet:Set,Di=null;function rw(n,r){if(n=n.containerInfo,Nd=Uc,n=Hm(n),Ju(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var S=0,k=-1,M=-1,Z=0,ce=0,fe=n,J=null;t:for(;;){for(var se;fe!==l||m!==0&&fe.nodeType!==3||(k=S+m),fe!==g||u!==0&&fe.nodeType!==3||(M=S+u),fe.nodeType===3&&(S+=fe.nodeValue.length),(se=fe.firstChild)!==null;)J=fe,fe=se;for(;;){if(fe===n)break t;if(J===l&&++Z===m&&(k=S),J===g&&++ce===u&&(M=S),(se=fe.nextSibling)!==null)break;fe=J,J=fe.parentNode}fe=se}l=k===-1||M===-1?null:{start:k,end:M}}else l=null}l=l||{start:0,end:0}}else l=null;for(Td={focusedElem:n,selectionRange:l},Uc=!1,Di=r;Di!==null;)if(r=Di,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Di=n;else for(;Di!==null;){switch(r=Di,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[st]=n,ri(g),u=g;break e;case"link":var S=B_("link","href",m).get(u+(l.href||""));if(S){for(var k=0;k$t&&(S=$t,$t=qe,qe=S);var F=Pm(k,qe),L=Pm(k,$t);if(F&&L&&(se.rangeCount!==1||se.anchorNode!==F.node||se.anchorOffset!==F.offset||se.focusNode!==L.node||se.focusOffset!==L.offset)){var X=fe.createRange();X.setStart(F.node,F.offset),se.removeAllRanges(),qe>$t?(se.addRange(X),se.extend(L.node,L.offset)):(X.setEnd(L.node,L.offset),se.addRange(X))}}}}for(fe=[],se=k;se=se.parentNode;)se.nodeType===1&&fe.push({element:se,left:se.scrollLeft,top:se.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=fd,fd=null;var g=gs,S=Wr;if(Ni=0,Ha=gs=null,Wr=0,(Dt&6)!==0)throw Error(s(331));var k=Dt;if(Dt|=4,Ix(g.current),Ox(g,g.current,S,l),Dt=k,Wl(0,!1),We&&typeof We.onPostCommitFiberRoot=="function")try{We.onPostCommitFiberRoot(ct,g)}catch{}return!0}finally{B.p=m,A.T=u,n_(n,r)}}function s_(n,r,l){r=Vn(l,r),r=Gh(n.stateNode,r,2),n=cs(n,r,2),n!==null&&(oe(n,2),vr(n))}function Pt(n,r,l){if(n.tag===3)s_(n,n,l);else for(;r!==null;){if(r.tag===3){s_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ms===null||!ms.has(u))){n=Vn(l,n),l=ax(2),u=cs(r,l,2),u!==null&&(lx(l,u,r,n),oe(u,2),vr(u));break}}r=r.return}}function xd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new lw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(cd=!0,m.add(l),n=dw.bind(null,n,r,l),r.then(n,n))}function dw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Wt===n&&(yt&l)===l&&(ui===4||ui===3&&(yt&62914560)===yt&&300>Ct()-wc?(Dt&2)===0&&Ua(n,0):ud|=l,Ia===yt&&(Ia=0)),vr(n)}function a_(n,r){r===0&&(r=qt()),n=Is(n,r),n!==null&&(oe(n,r),vr(n))}function fw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),a_(n,l)}function pw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),a_(n,l)}function mw(n,r){return Je(n,r)}var Ac=null,Fa=null,_d=!1,Rc=!1,bd=!1,_s=0;function vr(n){n!==Fa&&n.next===null&&(Fa===null?Ac=Fa=n:Fa=Fa.next=n),Rc=!0,_d||(_d=!0,xw())}function Wl(n,r){if(!bd&&Rc){bd=!0;do for(var l=!1,u=Ac;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var S=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-pt(42|n)+1)-1,g&=m&~(S&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,u_(u,g))}else g=yt,g=mt(u,u===Wt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Qe(u,g)||(l=!0,u_(u,g));u=u.next}while(l);bd=!1}}function gw(){l_()}function l_(){Rc=_d=!1;var n=0;_s!==0&&Nw()&&(n=_s);for(var r=Ct(),l=null,u=Ac;u!==null;){var m=u.next,g=o_(u,r);g===0?(u.next=null,l===null?Ac=m:l.next=m,m===null&&(Fa=l)):(l=u,(n!==0||(g&3)!==0)&&(Rc=!0)),u=m}Ni!==0&&Ni!==5||Wl(n),_s!==0&&(_s=0)}function o_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ce=M.transferSize,fe=M.initiatorType;ce&&__(fe)&&(M=M.responseEnd,S+=ce*(M"u"?null:document;function A_(n,r,l){var u=qa;if(u&&typeof r=="string"&&r){var m=Ei(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),j_.has(m)||(j_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Ki(r,"link",n),ri(r),u.head.appendChild(r)))}}function Ow(n){Gr.D(n),A_("dns-prefetch",n,null)}function zw(n,r){Gr.C(n,r),A_("preconnect",n,r)}function Pw(n,r,l){Gr.L(n,r,l);var u=qa;if(u&&n&&r){var m='link[rel="preload"][as="'+Ei(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Ei(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Ei(l.imageSizes)+'"]')):m+='[href="'+Ei(n)+'"]';var g=m;switch(r){case"style":g=Wa(n);break;case"script":g=Ga(n)}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(Vl(g))||r==="script"&&u.querySelector(Xl(g))||(r=u.createElement("link"),Ki(r,"link",n),ri(r),u.head.appendChild(r)))}}function Iw(n,r){Gr.m(n,r);var l=qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Ei(u)+'"][href="'+Ei(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ga(n)}if(!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(Xl(g)))return}u=l.createElement("link"),Ki(u,"link",n),ri(u),l.head.appendChild(u)}}}function Hw(n,r,l){Gr.S(n,r,l);var u=qa;if(u&&n){var m=qn(u).hoistableStyles,g=Wa(n);r=r||"default";var S=m.get(g);if(!S){var k={loading:0,preload:null};if(S=u.querySelector(Vl(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=tr.get(g))&&Ld(n,l);var M=S=u.createElement("link");ri(M),Ki(M,"link",n),M._p=new Promise(function(Z,ce){M.onload=Z,M.onerror=ce}),M.addEventListener("load",function(){k.loading|=1}),M.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Oc(S,r,u)}S={type:"stylesheet",instance:S,count:1,state:k},m.set(g,S)}}}function Uw(n,r){Gr.X(n,r);var l=qa;if(l&&n){var u=qn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0},r),(r=tr.get(m))&&Od(n,r),g=l.createElement("script"),ri(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function $w(n,r){Gr.M(n,r);var l=qa;if(l&&n){var u=qn(l).hoistableScripts,m=Ga(n),g=u.get(m);g||(g=l.querySelector(Xl(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=tr.get(m))&&Od(n,r),g=l.createElement("script"),ri(g),Ki(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function R_(n,r,l,u){var m=(m=ue.current)?Lc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Wa(l.href),l=qn(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Wa(l.href);var g=qn(m).hoistableStyles,S=g.get(n);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,S),(g=m.querySelector(Vl(n)))&&!g._p&&(S.instance=g,S.state.loading=5),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||Fw(m,n,l,S.state))),r&&u===null)throw Error(s(528,""));return S}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ga(l),l=qn(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Wa(n){return'href="'+Ei(n)+'"'}function Vl(n){return'link[rel="stylesheet"]['+n+"]"}function M_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function Fw(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),ri(r),n.head.appendChild(r))}function Ga(n){return'[src="'+Ei(n)+'"]'}function Xl(n){return"script[async]"+n}function D_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Ei(l.href)+'"]');if(u)return r.instance=u,ri(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"),ri(u),Ki(u,"style",m),Oc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Wa(l.href);var g=n.querySelector(Vl(m));if(g)return r.state.loading|=4,r.instance=g,ri(g),g;u=M_(l),(m=tr.get(m))&&Ld(u,m),g=(n.ownerDocument||n).createElement("link"),ri(g);var S=g;return S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),Ki(g,"link",u),r.state.loading|=4,Oc(g,l.precedence,n),r.instance=g;case"script":return g=Ga(l.src),(m=n.querySelector(Xl(g)))?(r.instance=m,ri(m),m):(u=l,(m=tr.get(g))&&(u=x({},l),Od(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),ri(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,Oc(u,l.precedence,n));return r.instance}function Oc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,S=0;S title"):null)}function qw(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function O_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Ww(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Wa(u.href),g=r.querySelector(Vl(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Pc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,ri(g);return}g=r.ownerDocument||r,u=M_(u),(m=tr.get(m))&&Ld(u,m),g=g.createElement("link"),ri(g);var S=g;S._p=new Promise(function(k,M){S.onload=k,S.onerror=M}),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=Pc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var zd=0;function Gw(n,r){return n.stylesheets&&n.count===0&&Hc(n,n.stylesheets),0zd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Pc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Ic=null;function Hc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Ic=new Map,r.forEach(Yw,n),Ic=null,Pc.call(n))}function Yw(n,r){if(!(r.state.loading&4)){var l=Ic.get(n);if(l)var u=l.get(null);else{l=new Map,Ic.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Gd.exports=uC(),Gd.exports}var dC=hC();const fC=Du(dC);function pC({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 mC({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 Xd="http://localhost:7777";function Cy({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,z)=>fetch(E,{...z,headers:{...z==null?void 0:z.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Xd}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${Xd}/api/wallet/create`,{method:"POST"}),z=await E.json();if(!E.ok)throw new Error(z.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},y=async E=>{c(E.walletId||E.name),_(null);try{const z=await x(`${Xd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),O=await z.json();if(!z.ok)throw new Error(O.error||"Wallet switch failed");b()}catch(z){_(z instanceof Error?z.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},j=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:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),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:j(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:()=>y(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),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 Su(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const zp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function gC({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),[y,N]=w.useState("AI Writer"),[j,E]=w.useState(""),[z,O]=w.useState(""),[W,q]=w.useState(!1),[D,te]=w.useState(null),[de,_e]=w.useState(""),[P,ae]=w.useState(null),[G,Y]=w.useState(!1),[Q,I]=w.useState(null),[A,B]=w.useState(null),[U,ge]=w.useState(null),T=w.useCallback((re,ue)=>fetch(re,{...ue,headers:{...ue==null?void 0:ue.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 R=async()=>{if(!y.trim()){te("Agent name is required");return}if(!j.trim()){te("Description is required");return}q(!0),te(null);try{const re=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:y,description:j,...z.trim()&&{genre:z}})}),ue=await re.json();if(!re.ok)throw new Error(ue.error||"Registration failed");v({linked:!0,agentId:ue.agentId,owsWallet:ue.owsWallet,txHash:ue.txHash})}catch(re){te(re instanceof Error?re.message:"Registration failed")}q(!1)},V=async()=>{if(!de.trim()||!/^0x[a-fA-F0-9]{40}$/.test(de)){I("Enter a valid wallet address (0x...)");return}Y(!0),I(null),ae(null);try{const re=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:de})}),ue=await re.json();if(!re.ok)throw new Error(ue.error||"Failed to generate binding code");ae(ue)}catch(re){I(re instanceof Error?re.message:"Failed to generate binding code")}Y(!1)},C=async(re,ue)=>{await navigator.clipboard.writeText(re),B(ue),setTimeout(()=>B(null),2e3)},K=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 ue=await re.json();throw new Error(ue.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:y,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:j,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:z,onChange:re=>O(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"})]}),D&&d.jsx("p",{className:"text-error text-xs",children:D}),d.jsx("button",{onClick:R,disabled:W||!y.trim()||!j.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"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:U!=null&&U.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:U!=null&&U.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:(U==null?void 0:U.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:(U==null?void 0:U.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:U!=null&&U.codex.installed?U.codex.auth==="ok"?"ok":"unclear":"—"})]}),Su(U)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:zp}),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:U!=null&&U.checkedAt?new Date(U.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:de,onChange:re=>_e(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"}),Q&&d.jsx("p",{className:"text-error text-xs",children:Q}),d.jsx("button",{onClick:V,disabled:G||!de.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:G?"Generating...":"Generate Binding Code"}),P&&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:P.signature}),d.jsx("button",{onClick:()=>C(P.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:P.owsWallet}),d.jsx("button",{onClick:()=>C(P.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"})]})]}),P.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:P.agentId}),d.jsx("button",{onClick:()=>C(String(P.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(Cy,{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:K,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 xC="http://localhost:7777";function _C({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(`${xC}/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 bC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},vC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function yC({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),y=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const D=await q.json();h(D.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const D=await q.json();f(D.stories)}}catch{}},[e]),j=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),y())}catch{}},[e,N,y]);w.useEffect(()=>{y();const q=setInterval(y,5e3);return()=>clearInterval(q)},[y]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(D=>{const te=new Set(D);return te.has(q)?te.delete(q):te.add(q),te})},z=q=>{var te;const D=q.map(de=>{var _e;return{file:de.file,num:(_e=de.file.match(/^plot-(\d+)\.md$/))==null?void 0:_e[1]}}).filter(de=>de.num!=null).sort((de,_e)=>parseInt(_e.num)-parseInt(de.num));return D.length>0?D[0].file:q.some(de=>de.file==="genesis.md")?"genesis.md":q.some(de=>de.file==="structure.md")?"structure.md":((te=q[0])==null?void 0:te.file)??null},O=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const D=z(q.files);D&&s(q.name,D)}},W=q=>{const D=te=>{if(te==="structure.md")return 0;if(te==="genesis.md")return 1;const de=te.match(/^plot-(\d+)\.md$/);return de?2+parseInt(de[1]):100};return[...q].sort((te,de)=>D(te.file)-D(de.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:()=>j(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:()=>O(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:W(q.files).map(D=>{const te=t===q.name&&i===D.file;return d.jsxs("button",{onClick:()=>s(q.name,D.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${te?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:vC[D.status],children:bC[D.status]}),d.jsx("span",{className:"truncate font-mono",children:D.file})]},D.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 ky=Object.defineProperty,SC=Object.getOwnPropertyDescriptor,wC=(e,t)=>{for(var i in t)ky(e,i,{get:t[i],enumerable:!0})},fi=(e,t,i,s)=>{for(var a=s>1?void 0:s?SC(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&&ky(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),ab="Terminal input",zf={get:()=>ab,set:e=>ab=e},lb="Too much output to announce, navigate to rows manually to read",Pf={get:()=>lb,set:e=>lb=e};function CC(e){return e.replace(/\r?\n/g,"\r")}function kC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function EC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function NC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Ey(a,t,i,s)}}function Ey(e,t,i,s){e=CC(e),e=kC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ny(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function ob(e,t,i,s,a){Ny(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function js(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Bu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var TC=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}},jC=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 y=0,N;for(;(N=this.interim[++y]&63)&&y<4;)v<<=6,v|=N;let j=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=j-y;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[y++]=N,v<<=6,v|=N&63}b||(j===2?v<128?f--:t[s++]=v:j===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}},Ty="",Rs=" ",Ao=class jy{constructor(){this.fg=0,this.bg=0,this.extended=new wu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new jy;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},wu=class Ay{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 Ay(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},lr=class Ry extends Ao{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wu,this.combinedData=""}static fromCharData(t){let i=new Ry;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?js(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},cb="di$target",If="di$dependencies",Zd=new Map;function AC(e){return e[If]||[]}function $i(e){if(Zd.has(e))return Zd.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");RC(t,i,a)};return t._id=e,Zd.set(e,t),t}function RC(e,t,i){t[cb]===t?t[If].push({id:e,index:i}):(t[If]=[{id:e,index:i}],t[cb]=t)}var mn=$i("BufferService"),My=$i("CoreMouseService"),ca=$i("CoreService"),MC=$i("CharsetService"),Pp=$i("InstantiationService"),Dy=$i("LogService"),gn=$i("OptionsService"),By=$i("OscLinkService"),DC=$i("UnicodeService"),Ro=$i("DecorationService"),Hf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new lr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,j,v):BC(N,j),hover:(N,j)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,j,v)},leave:(N,j)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,j,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Hf=fi([Re(0,mn),Re(1,gn),Re(2,By)],Hf);function BC(e,t){if(confirm(`Do you want to navigate to ${t}? + +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Lu=$i("CharSizeService"),Qr=$i("CoreBrowserService"),Ip=$i("MouseService"),Jr=$i("RenderService"),LC=$i("SelectionService"),Ly=$i("CharacterJoinerService"),ol=$i("ThemeService"),Oy=$i("LinkProviderService"),OC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ub.isErrorNoTelemetry(e)?new ub(e.message+` + +`+e.stack):new Error(e.message+` + +`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},zC=new OC;function hu(e){PC(e)||zC.onUnexpectedError(e)}var Uf="Canceled";function PC(e){return e instanceof IC?!0:e instanceof Error&&e.name===Uf&&e.message===Uf}var IC=class extends Error{constructor(){super(Uf),this.name=this.message}};function HC(e){return new Error(`Illegal argument: ${e}`)}var ub=class $f extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $f)return t;let i=new $f;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ff=class zy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,zy.prototype)}};function In(e,t=0){return e[e.length-(1+t)]}var UC;(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})(UC||(UC={}));function $C(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Py;(e=>{function t(W){return W&&typeof W=="object"&&typeof W[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(W){yield W}e.single=a;function o(W){return t(W)?W:a(W)}e.wrap=o;function c(W){return W||i}e.from=c;function*h(W){for(let q=W.length-1;q>=0;q--)yield W[q]}e.reverse=h;function p(W){return!W||W[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(W){return W[Symbol.iterator]().next().value}e.first=f;function _(W,q){let D=0;for(let te of W)if(q(te,D++))return!0;return!1}e.some=_;function x(W,q){for(let D of W)if(q(D))return D}e.find=x;function*b(W,q){for(let D of W)q(D)&&(yield D)}e.filter=b;function*v(W,q){let D=0;for(let te of W)yield q(te,D++)}e.map=v;function*y(W,q){let D=0;for(let te of W)yield*q(te,D++)}e.flatMap=y;function*N(...W){for(let q of W)yield*q}e.concat=N;function j(W,q,D){let te=D;for(let de of W)te=q(te,de);return te}e.reduce=j;function*E(W,q,D=W.length){for(q<0&&(q+=W.length),D<0?D+=W.length:D>W.length&&(D=W.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 FC(...e){return ti(()=>aa(e))}function ti(e){return{dispose:$C(()=>{e()})}}var Iy=class Hy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{aa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Hy.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)}};Iy.DISABLE_DISPOSED_WARNING=!1;var Ms=Iy,ft=class{constructor(){this._store=new Ms,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ft.None=Object.freeze({dispose(){}});var sl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Zr=typeof window=="object"?window:globalThis,qf=class Wf{constructor(t){this.element=t,this.next=Wf.Undefined,this.prev=Wf.Undefined}};qf.Undefined=new qf(void 0);var si=qf,hb=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}},qC=globalThis.performance&&typeof globalThis.performance.now=="function",WC=class Uy{static create(t){return new Uy(t)}constructor(t){this._now=qC&&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}},Zi;(e=>{e.None=()=>ft.None;function t(G,Y){return x(G,()=>{},0,void 0,!0,void 0,Y)}e.defer=t;function i(G){return(Y,Q=null,I)=>{let A=!1,B;return B=G(U=>{if(!A)return B?B.dispose():A=!0,Y.call(Q,U)},null,I),A&&B.dispose(),B}}e.once=i;function s(G,Y,Q){return f((I,A=null,B)=>G(U=>I.call(A,Y(U)),null,B),Q)}e.map=s;function a(G,Y,Q){return f((I,A=null,B)=>G(U=>{Y(U),I.call(A,U)},null,B),Q)}e.forEach=a;function o(G,Y,Q){return f((I,A=null,B)=>G(U=>Y(U)&&I.call(A,U),null,B),Q)}e.filter=o;function c(G){return G}e.signal=c;function h(...G){return(Y,Q=null,I)=>{let A=FC(...G.map(B=>B(U=>Y.call(Q,U))));return _(A,I)}}e.any=h;function p(G,Y,Q,I){let A=Q;return s(G,B=>(A=Y(A,B),A),I)}e.reduce=p;function f(G,Y){let Q,I={onWillAddFirstListener(){Q=G(A.fire,A)},onDidRemoveLastListener(){Q==null||Q.dispose()}},A=new we(I);return Y==null||Y.add(A),A.event}function _(G,Y){return Y instanceof Array?Y.push(G):Y&&Y.add(G),G}function x(G,Y,Q=100,I=!1,A=!1,B,U){let ge,T,R,V=0,C,K={leakWarningThreshold:B,onWillAddFirstListener(){ge=G(ue=>{V++,T=Y(T,ue),I&&!R&&(re.fire(T),T=void 0),C=()=>{let $=T;T=void 0,R=void 0,(!I||V>1)&&re.fire($),V=0},typeof Q=="number"?(clearTimeout(R),R=setTimeout(C,Q)):R===void 0&&(R=0,queueMicrotask(C))})},onWillRemoveListener(){A&&V>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,ge.dispose()}},re=new we(K);return U==null||U.add(re),re.event}e.debounce=x;function b(G,Y=0,Q){return e.debounce(G,(I,A)=>I?(I.push(A),I):[A],Y,void 0,!0,void 0,Q)}e.accumulate=b;function v(G,Y=(I,A)=>I===A,Q){let I=!0,A;return o(G,B=>{let U=I||!Y(B,A);return I=!1,A=B,U},Q)}e.latch=v;function y(G,Y,Q){return[e.filter(G,Y,Q),e.filter(G,I=>!Y(I),Q)]}e.split=y;function N(G,Y=!1,Q=[],I){let A=Q.slice(),B=G(T=>{A?A.push(T):ge.fire(T)});I&&I.add(B);let U=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new we({onWillAddFirstListener(){B||(B=G(T=>ge.fire(T)),I&&I.add(B))},onDidAddFirstListener(){A&&(Y?setTimeout(U):U())},onDidRemoveLastListener(){B&&B.dispose(),B=null}});return I&&I.add(ge),ge.event}e.buffer=N;function j(G,Y){return(Q,I,A)=>{let B=Y(new z);return G(function(U){let ge=B.evaluate(U);ge!==E&&Q.call(I,ge)},void 0,A)}}e.chain=j;let E=Symbol("HaltChainable");class z{constructor(){this.steps=[]}map(Y){return this.steps.push(Y),this}forEach(Y){return this.steps.push(Q=>(Y(Q),Q)),this}filter(Y){return this.steps.push(Q=>Y(Q)?Q:E),this}reduce(Y,Q){let I=Q;return this.steps.push(A=>(I=Y(I,A),I)),this}latch(Y=(Q,I)=>Q===I){let Q=!0,I;return this.steps.push(A=>{let B=Q||!Y(A,I);return Q=!1,I=A,B?A:E}),this}evaluate(Y){for(let Q of this.steps)if(Y=Q(Y),Y===E)break;return Y}}function O(G,Y,Q=I=>I){let I=(...ge)=>U.fire(Q(...ge)),A=()=>G.on(Y,I),B=()=>G.removeListener(Y,I),U=new we({onWillAddFirstListener:A,onDidRemoveLastListener:B});return U.event}e.fromNodeEventEmitter=O;function W(G,Y,Q=I=>I){let I=(...ge)=>U.fire(Q(...ge)),A=()=>G.addEventListener(Y,I),B=()=>G.removeEventListener(Y,I),U=new we({onWillAddFirstListener:A,onDidRemoveLastListener:B});return U.event}e.fromDOMEventEmitter=W;function q(G){return new Promise(Y=>i(G)(Y))}e.toPromise=q;function D(G){let Y=new we;return G.then(Q=>{Y.fire(Q)},()=>{Y.fire(void 0)}).finally(()=>{Y.dispose()}),Y.event}e.fromPromise=D;function te(G,Y){return G(Q=>Y.fire(Q))}e.forward=te;function de(G,Y,Q){return Y(Q),G(I=>Y(I))}e.runAndSubscribe=de;class _e{constructor(Y,Q){this._observable=Y,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{Y.addObserver(this)},onDidRemoveLastListener:()=>{Y.removeObserver(this)}};this.emitter=new we(I),Q&&Q.add(this.emitter)}beginUpdate(Y){this._counter++}handlePossibleChange(Y){}handleChange(Y,Q){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 P(G,Y){return new _e(G,Y).emitter.event}e.fromObservable=P;function ae(G){return(Y,Q,I)=>{let A=0,B=!1,U={beginUpdate(){A++},endUpdate(){A--,A===0&&(G.reportChanges(),B&&(B=!1,Y.call(Q)))},handlePossibleChange(){},handleChange(){B=!0}};G.addObserver(U),G.reportChanges();let ge={dispose(){G.removeObserver(U)}};return I instanceof Ms?I.add(ge):Array.isArray(I)&&I.push(ge),ge}}e.fromObservableLight=ae})(Zi||(Zi={}));var Gf=class Yf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Yf._idPool++}`,Yf.all.add(this)}start(t){this._stopWatch=new WC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Gf.all=new Set,Gf._idPool=0;var GC=Gf,YC=-1,$y=class Fy{constructor(t,i,s=(Fy._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],y=new ZC(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||hu)(y),ft.None}if(this._disposed)return ft.None;i&&(t=t.bind(i));let a=new Qd(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=VC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof Qd?(this._deliveryQueue??(this._deliveryQueue=new tk),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=ti(()=>{o==null||o(),this._removeListener(a)});return s instanceof Ms?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*JC<=i.length){let f=0;for(let _=0;_0}},tk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Kf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new 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}};Kf.INSTANCE=new Kf;var Hp=Kf;function ik(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Hp.INSTANCE.onDidChangeZoomLevel;function nk(e){return Hp.INSTANCE.getZoomFactor(e)}Hp.INSTANCE.onDidChangeFullscreen;var cl=typeof navigator=="object"?navigator.userAgent:"",Vf=cl.indexOf("Firefox")>=0,rk=cl.indexOf("AppleWebKit")>=0,Up=cl.indexOf("Chrome")>=0,sk=!Up&&cl.indexOf("Safari")>=0;cl.indexOf("Electron/")>=0;cl.indexOf("Android")>=0;var Jd=!1;if(typeof Zr.matchMedia=="function"){let e=Zr.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Zr.matchMedia("(display-mode: fullscreen)");Jd=e.matches,ik(Zr,e,({matches:i})=>{Jd&&t.matches||(Jd=i)})}var tl="en",Xf=!1,Zf=!1,du=!1,Wy=!1,Kc,fu=tl,db=tl,ak,mr,sa=globalThis,Xi,yy;typeof sa.vscode<"u"&&typeof sa.vscode.process<"u"?Xi=sa.vscode.process:typeof process<"u"&&typeof((yy=process==null?void 0:process.versions)==null?void 0:yy.node)=="string"&&(Xi=process);var Sy,lk=typeof((Sy=Xi==null?void 0:Xi.versions)==null?void 0:Sy.electron)=="string",ok=lk&&(Xi==null?void 0:Xi.type)==="renderer",wy;if(typeof Xi=="object"){Xf=Xi.platform==="win32",Zf=Xi.platform==="darwin",du=Xi.platform==="linux",du&&Xi.env.SNAP&&Xi.env.SNAP_REVISION,Xi.env.CI||Xi.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Kc=tl,fu=tl;let e=Xi.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Kc=t.userLocale,db=t.osLocale,fu=t.resolvedLanguage||tl,ak=(wy=t.languagePack)==null?void 0:wy.translationsConfigFile}catch{}Wy=!0}else typeof navigator=="object"&&!ok?(mr=navigator.userAgent,Xf=mr.indexOf("Windows")>=0,Zf=mr.indexOf("Macintosh")>=0,(mr.indexOf("Macintosh")>=0||mr.indexOf("iPad")>=0||mr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,du=mr.indexOf("Linux")>=0,(mr==null?void 0:mr.indexOf("Mobi"))>=0,fu=globalThis._VSCODE_NLS_LANGUAGE||tl,Kc=navigator.language.toLowerCase(),db=Kc):console.error("Unable to resolve platform.");var Gy=Xf,Nr=Zf,ck=du,fb=Wy,Tr=mr,ks=fu,uk;(e=>{function t(){return ks}e.value=t;function i(){return ks.length===2?ks==="en":ks.length>=3?ks[0]==="e"&&ks[1]==="n"&&ks[2]==="-":!1}e.isDefaultVariant=i;function s(){return ks==="en"}e.isDefault=s})(uk||(uk={}));var hk=typeof sa.postMessage=="function"&&!sa.importScripts;(()=>{if(hk){let e=[];sa.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),sa.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var dk=!!(Tr&&Tr.indexOf("Chrome")>=0);Tr&&Tr.indexOf("Firefox")>=0;!dk&&Tr&&Tr.indexOf("Safari")>=0;Tr&&Tr.indexOf("Edg/")>=0;Tr&&Tr.indexOf("Android")>=0;var Ka=typeof navigator=="object"?navigator:{};fb||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ka&&Ka.clipboard&&Ka.clipboard.writeText,fb||Ka&&Ka.clipboard&&Ka.clipboard.readText;var $p=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ef=new $p,pb=new $p,mb=new $p,fk=new Array(230),Yy;(e=>{function t(h){return ef.keyCodeToStr(h)}e.toString=t;function i(h){return ef.strToKeyCode(h)}e.fromString=i;function s(h){return pb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return mb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return pb.strToKeyCode(h)||mb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return ef.keyCodeToStr(h)}e.toElectronAccelerator=c})(Yy||(Yy={}));var pk=class Ky{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 Ky&&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 mk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},mk=class{constructor(e){if(e.length===0)throw HC("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 Ck?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Zi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Vy})})(wk||(wk={}));var Ck=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?Vy:(this._emitter||(this._emitter=new we),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Fp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ff("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},kk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Ff("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ti(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ek;(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})(Ek||(Ek={}));var bb=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 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 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())}};bb.EMPTY=bb.fromArray([]);var{getWindow:kr,getWindowId:Nk,onDidRegisterWindow:Tk}=(function(){let e=new Map,t={window:Zr,disposables:new Ms};e.set(Zr.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 ft.None;let h=new Ms,p={window:c,disposables:h.add(new Ms)};return e.set(c.vscodeWindowId,p),h.add(ti(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ke(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:Zr},getDocument(c){return kr(c).document}}})(),jk=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 jk(e,t,i,s)}var vb=function(e,t,i,s){return Ke(e,t,i,s)},qp,Ak=class extends kk{constructor(e){super(),this.defaultTarget=e&&kr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},yb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){hu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(yb.sort),c.shift().execute();s.set(o,!1)};qp=(o,c,h=0)=>{let p=Nk(o),f=new yb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Rk(e){let t=e.getBoundingClientRect(),i=kr(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"},Mk=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=kn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=kn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=kn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=kn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=kn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=kn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=kn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=kn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=kn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=kn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=kn(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=kn(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=kn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=kn(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 kn(e){return typeof e=="number"?`${e}px`:e}function bo(e){return new Mk(e)}var Xy=class{constructor(){this._hooks=new Ms,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ti(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=kr(e)}this._hooks.add(Ke(o,Bi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ke(o,Bi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Dk(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 wr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(wr||(wr={}));var po=class nn extends ft{constructor(){super(),this.dispatched=!1,this.targets=new hb,this.ignoreTargets=new hb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Zi.runAndSubscribe(Tk,({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:Zr,disposables:this._store}))}static addTarget(t){if(!nn.isTouchDevice())return ft.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.targets.push(t);return ti(i)}static ignoreTarget(t){if(!nn.isTouchDevice())return ft.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.ignoreTargets.push(t);return ti(i)}static isTouchDevice(){return"ontouchstart"in Zr||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=nn.HOLD_DELAY&&Math.abs(p.initialPageX-In(p.rollingPageX))<30&&Math.abs(p.initialPageY-In(p.rollingPageY))<30){let _=this.newGestureEvent(wr.Contextmenu,p.initialTarget);_.pageX=In(p.rollingPageX),_.pageY=In(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=In(p.rollingPageX),x=In(p.rollingPageY),b=In(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],y=x-p.rollingPageY[0],N=[...this.targets].filter(j=>p.initialTarget instanceof Node&&j.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(y)/b,y>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(wr.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===wr.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===wr.Change||t.type===wr.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=qp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,y=!0;a+=nn.SCROLL_FRICTION*x,h+=nn.SCROLL_FRICTION*x,a>0&&(y=!1,b=o*a*x),h>0&&(y=!1,v=p*h*x);let N=this.newGestureEvent(wr.Change);N.translationX=b,N.translationY=v,i.forEach(j=>j.dispatchEvent(N)),y||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)}};po.SCROLL_FRICTION=-.005,po.HOLD_DELAY=700,po.CLEAR_TAP_COUNT_TIME=400,fi([Dk],po,"isTouchDevice",1);var Bk=po,Wp=class extends ft{onclick(e,t){this._register(Ke(e,Bi.CLICK,i=>t(new Vc(kr(e),i))))}onmousedown(e,t){this._register(Ke(e,Bi.MOUSE_DOWN,i=>t(new Vc(kr(e),i))))}onmouseover(e,t){this._register(Ke(e,Bi.MOUSE_OVER,i=>t(new Vc(kr(e),i))))}onmouseleave(e,t){this._register(Ke(e,Bi.MOUSE_LEAVE,i=>t(new Vc(kr(e),i))))}onkeydown(e,t){this._register(Ke(e,Bi.KEY_DOWN,i=>t(new gb(i))))}onkeyup(e,t){this._register(Ke(e,Bi.KEY_UP,i=>t(new gb(i))))}oninput(e,t){this._register(Ke(e,Bi.INPUT,t))}onblur(e,t){this._register(Ke(e,Bi.BLUR,t))}onfocus(e,t){this._register(Ke(e,Bi.FOCUS,t))}onchange(e,t){this._register(Ke(e,Bi.CHANGE,t))}ignoreGesture(e){return Bk.ignoreTarget(e)}},Sb=11,Lk=class extends Wp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Sb+"px",this.domNode.style.height=Sb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Xy),this._register(vb(this.bgDomNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(vb(this.domNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Ak),this._pointerdownScheduleRepeatTimer=this._register(new Fp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,kr(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()}},Ok=class Qf{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Qf(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qf(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},zk=class extends ft{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 Ok(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Cb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Cb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},wb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function tf(e,t){let i=t-e;return function(s){return e+i*Hk(s)}}function Pk(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":"")))}},$k=140,Zy=class extends Wp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Uk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Xy),this._shouldRender=!0,this.domNode=bo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ke(this.domNode.domNode,Bi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Lk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=bo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ke(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=Rk(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(Gy&&c>$k){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()}},Qy=class ep{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ep(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let 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=ep._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),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}};tp.INSTANCE=new tp;var Yk=tp,Kk=class extends Wp{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=Xk(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 qk(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Fk(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=bo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=bo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=bo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Fp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=aa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Nr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new _b(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=aa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new _b(i))};this._mouseWheelToDispose.push(Ke(this._listenOnDomNode,Bi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Yk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Nr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=kb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=kb*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(),Wk)}},Vk=class extends Kk{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 Xk(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Nr&&(t.className+=" mac"),t}var ip=class extends ft{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new zk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>qp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Vk(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(Zi.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ti(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ti(()=>this._styleElement.remove())),this._register(Zi.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}};ip=fi([Re(2,mn),Re(3,Qr),Re(4,My),Re(5,ol),Re(6,gn),Re(7,Jr)],ip);var np=class extends ft{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ti(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};np=fi([Re(1,mn),Re(2,Qr),Re(3,Ro),Re(4,Jr)],np);var Zk=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)}},yr={full:0,left:0,center:0,right:0},Es={full:0,left:0,center:0,right:0},no={full:0,left:0,center:0,right:0},Cu=class extends ft{constructor(e,t,i,s,a,o,c,h){var 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 Zk,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(ti(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Es.full=this._canvas.width,Es.left=e,Es.center=t,Es.right=e,this._refreshDrawHeightConstants(),no.full=1,no.left=1,no.center=1+Es.left,no.right=1+Es.left+Es.center}_refreshDrawHeightConstants(){yr.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);yr.left=t,yr.center=t,yr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(no[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-yr[e.position||"full"]/2),Es[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+yr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Cu=fi([Re(2,mn),Re(3,Ro),Re(4,Jr),Re(5,gn),Re(6,ol),Re(7,Qr)],Cu);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var pu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(pu||(pu={}));var Jy;(e=>e.ST=`${pe.ESC}\\`)(Jy||(Jy={}));var rp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};rp=fi([Re(2,mn),Re(3,gn),Re(4,ca),Re(5,Jr)],rp);var Li=0,Oi=0,zi=0,hi=0,Eb={css:"#00000000",rgba:0},ki;(e=>{function t(a,o,c,h){return h!==void 0?`#${Qs(a)}${Qs(o)}${Qs(c)}${Qs(h)}`:`#${Qs(a)}${Qs(o)}${Qs(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(ki||(ki={}));var Qt;(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,y=p.rgba>>16&255,N=p.rgba>>8&255;Li=v+Math.round((_-v)*hi),Oi=y+Math.round((x-y)*hi),zi=N+Math.round((b-N)*hi);let j=ki.toCss(Li,Oi,zi),E=ki.toRgba(Li,Oi,zi);return{css:j,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=mu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return ki.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]=mu.toChannels(f),{css:ki.toCss(Li,Oi,zi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[Li,Oi,zi]=mu.toChannels(p.rgba),{css:ki.toCss(Li,Oi,zi,hi),rgba:ki.toRgba(Li,Oi,zi,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})(Qt||(Qt={}));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 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),ki.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),hi=parseInt(a.slice(4,5).repeat(2),16),ki.toColor(Li,Oi,zi,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 Li=parseInt(o[1]),Oi=parseInt(o[2]),zi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),ki.toColor(Li,Oi,zi,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),[Li,Oi,zi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:ki.toRgba(Li,Oi,zi,hi),css:a}}e.toColor=s})(ai||(ai={}));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 mu;(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 Li=x+Math.round((p-x)*hi),Oi=b+Math.round((f-b)*hi),zi=v+Math.round((_-v)*hi),ki.toRgba(Li,Oi,zi)}e.blend=t;function i(c,h,p){let f=dn.relativeLuminance(c>>8),_=dn.relativeLuminance(h>>8);if(Yr(f,_)>8));if(y>8));return y>j?v:N}return v}let x=a(c,h,p),b=Yr(f,dn.relativeLuminance(x>>8));if(b>8));return b>y?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,y=h>>8&255,N=Yr(dn.relativeLuminance2(b,v,y),dn.relativeLuminance2(f,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Yr(dn.relativeLuminance2(b,v,y),dn.relativeLuminance2(f,_,x));return(b<<24|v<<16|y<<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,y=h>>8&255,N=Yr(dn.relativeLuminance2(b,v,y),dn.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})(mu||(mu={}));function Qs(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Yr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Rs.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=P,B=Y,U=this._workCell;if(b.length>0&&Y===b[0][0]&&A){let ye=b.shift(),rt=this._isCellInSelection(ye[0],t);for(z=ye[0]+1;z=ye[1]),A?(I=!0,U=new Qk(this._workCell,e.translateToString(!0,ye[0],ye[1]),ye[1]-ye[0]),B=ye[1]-1,Q=U.getWidth()):P=ye[1]}let ge=this._isCellInSelection(Y,t),T=i&&Y===o,R=G&&Y>=f&&Y<=_,V=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,ye=>{V=!0});let C=U.getChars()||Rs;if(C===" "&&(U.isUnderline()||U.isOverline())&&(C=" "),_e=Q*h-p.get(C,U.isBold(),U.isItalic()),!N)N=this._document.createElement("span");else if(j&&(ge&&de||!ge&&!de&&U.bg===O)&&(ge&&de&&v.selectionForeground||U.fg===W)&&U.extended.ext===q&&R===D&&_e===te&&!T&&!I&&!V&&A){U.isInvisible()?E+=Rs:E+=C,j++;continue}else j&&(N.textContent=E),N=this._document.createElement("span"),j=0,E="";if(O=U.bg,W=U.fg,q=U.extended.ext,D=R,te=_e,de=ge,I&&o>=Y&&o<=B&&(o=Y),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ae.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ae.push("xterm-cursor-blink"),ae.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ae.push("xterm-cursor-outline");break;case"block":ae.push("xterm-cursor-block");break;case"bar":ae.push("xterm-cursor-bar");break;case"underline":ae.push("xterm-cursor-underline");break}}if(U.isBold()&&ae.push("xterm-bold"),U.isItalic()&&ae.push("xterm-italic"),U.isDim()&&ae.push("xterm-dim"),U.isInvisible()?E=Rs:E=U.getChars()||Rs,U.isUnderline()&&(ae.push(`xterm-underline-${U.extended.underlineStyle}`),E===" "&&(E=" "),!U.isUnderlineColorDefault()))if(U.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${Ao.toColorRGB(U.getUnderlineColor()).join(",")})`;else{let ye=U.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&U.isBold()&&ye<8&&(ye+=8),N.style.textDecorationColor=v.ansi[ye].css}U.isOverline()&&(ae.push("xterm-overline"),E===" "&&(E=" ")),U.isStrikethrough()&&ae.push("xterm-strikethrough"),R&&(N.style.textDecoration="underline");let K=U.getFgColor(),re=U.getFgColorMode(),ue=U.getBgColor(),$=U.getBgColorMode(),le=!!U.isInverse();if(le){let ye=K;K=ue,ue=ye;let rt=re;re=$,$=rt}let be,Te,Le=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,ye=>{ye.options.layer!=="top"&&Le||(ye.backgroundColorRGB&&($=50331648,ue=ye.backgroundColorRGB.rgba>>8&16777215,be=ye.backgroundColorRGB),ye.foregroundColorRGB&&(re=50331648,K=ye.foregroundColorRGB.rgba>>8&16777215,Te=ye.foregroundColorRGB),Le=ye.options.layer==="top")}),!Le&&ge&&(be=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,ue=be.rgba>>8&16777215,$=50331648,Le=!0,v.selectionForeground&&(re=50331648,K=v.selectionForeground.rgba>>8&16777215,Te=v.selectionForeground)),Le&&ae.push("xterm-decoration-top");let ze;switch($){case 16777216:case 33554432:ze=v.ansi[ue],ae.push(`xterm-bg-${ue}`);break;case 50331648:ze=ki.toColor(ue>>16,ue>>8&255,ue&255),this._addStyle(N,`background-color:#${Nb((ue>>>0).toString(16),"0",6)}`);break;case 0:default:le?(ze=v.foreground,ae.push("xterm-bg-257")):ze=v.background}switch(be||U.isDim()&&(be=Qt.multiplyOpacity(ze,.5)),re){case 16777216:case 33554432:U.isBold()&&K<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(K+=8),this._applyMinimumContrast(N,ze,v.ansi[K],U,be,void 0)||ae.push(`xterm-fg-${K}`);break;case 50331648:let ye=ki.toColor(K>>16&255,K>>8&255,K&255);this._applyMinimumContrast(N,ze,ye,U,be,Te)||this._addStyle(N,`color:#${Nb(K.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,ze,v.foreground,U,be,Te)||le&&ae.push("xterm-fg-257")}ae.length&&(N.className=ae.join(" "),ae.length=0),!T&&!I&&!V&&A?j++:N.textContent=E,_e!==this.defaultSpacing&&(N.style.letterSpacing=`${_e}px`),x.push(N),Y=B}return N&&j&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||t2(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]}};sp=fi([Re(1,Ly),Re(2,gn),Re(3,Qr),Re(4,ca),Re(5,Ro),Re(6,ol)],sp);function Nb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},r2=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 s2(){return new r2}var nf="xterm-dom-renderer-owner-",ir="xterm-rows",Zc="xterm-fg-",Tb="xterm-bg-",ro="xterm-focus",Qc="xterm-selection",a2=1,ap=class extends ft{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=a2++,this._rowElements=[],this._selectionRenderModel=s2(),this.onRequestRedraw=this._register(new we).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(Qc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=i2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(y=>this._injectCss(y))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(sp,document),this._element.classList.add(nf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(y=>this._handleLinkHover(y))),this._register(this._linkifier2.onHideLinkUnderline(y=>this._handleLinkLeave(y))),this._register(ti(()=>{this._element.classList.remove(nf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new n2(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: ${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} .${ir}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ro} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${ir}.${ro} .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} .${Qc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Qc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Qc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${Zc}${o} { color: ${c.css}; }${this._terminalSelector} .${Zc}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Tb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${Zc}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${Zc}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Tb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ro),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ro),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,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`.${nf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,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 y=v+h.ydisp,N=this._rowElements[v],j=h.lines.get(y);if(!N||!j)break;N.replaceChildren(...this._rowFactory.createRow(j,y,y===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};ap=fi([Re(7,Pp),Re(8,Lu),Re(9,gn),Re(10,mn),Re(11,ca),Re(12,Qr),Re(13,ol)],ap);var lp=class extends ft{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new we),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new o2(this._optionsService))}catch{this._measureStrategy=this._register(new l2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lp=fi([Re(2,gn)],lp);var e0=class extends ft{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},l2=class extends e0{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}},o2=class extends e0{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}},c2=class extends ft{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new u2(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(Zi.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}},u2=class extends ft{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new sl),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(ti(()=>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)}},h2=class extends ft{constructor(){super(),this.linkProviders=[],this._register(ti(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Gp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function d2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Gp(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 op=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return d2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Gp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};op=fi([Re(0,Jr),Re(1,Lu)],op);var f2=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=[]}},t0={};wC(t0,{getSafariVersion:()=>m2,isChromeOS:()=>s0,isFirefox:()=>i0,isIpad:()=>g2,isIphone:()=>x2,isLegacyEdge:()=>p2,isLinux:()=>Yp,isMac:()=>Eu,isNode:()=>Ou,isSafari:()=>n0,isWindows:()=>r0});var Ou=typeof process<"u"&&"title"in process,Mo=Ou?"node":navigator.userAgent,Do=Ou?"node":navigator.platform,i0=Mo.includes("Firefox"),p2=Mo.includes("Edge"),n0=/^((?!chrome|android).)*safari/i.test(Mo);function m2(){if(!n0)return 0;let e=Mo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Eu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Do),g2=Do==="iPad",x2=Do==="iPhone",r0=["Windows","Win16","Win32","WinCE"].includes(Do),Yp=Do.indexOf("Linux")>=0,s0=/\bCrOS\b/.test(Mo),a0=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()}},_2=class extends a0{_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())}}},b2=class extends a0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Nu=!Ou&&"requestIdleCallback"in window?b2:_2,v2=class{constructor(){this._queue=new Nu}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cp=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new sl),this._pausedResizeTask=new v2,this._observerDisposable=this._register(new sl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new 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 f2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new y2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ti(()=>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=ti(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cp=fi([Re(2,gn),Re(3,Lu),Re(4,ca),Re(5,Ro),Re(6,mn),Re(7,Qr),Re(8,ol)],cp);var y2=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 S2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return k2(a,o,e,t,i,s)+zu(o,t,i,s)+E2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Co(Math.abs(a-e),wo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=C2(o>t?e:a,i)+(h-1)*i.cols+1+w2(o>t?a:e);return Co(p,wo(c,s))}function w2(e,t){return e-1}function C2(e,t){return t.cols-e}function k2(e,t,i,s,a,o){return zu(t,s,a,o).length===0?"":Co(o0(e,t,e,t-la(t,a),!1,a).length,wo("D",o))}function zu(e,t,i,s){let a=e-la(e,i),o=t-la(t,i),c=Math.abs(a-o)-N2(e,t,i);return Co(c,wo(l0(e,t),s))}function E2(e,t,i,s,a,o){let c;zu(t,s,a,o).length>0?c=s-la(s,a):c=t;let h=s,p=T2(e,t,i,s,a,o);return Co(o0(e,c,i,h,p==="C",a).length,wo(p,o))}function N2(e,t,i){var c;let s=0,a=e-la(e,i),o=t-la(t,i);for(let h=0;h=0&&e0?c=s-la(s,a):c=t,e=i&&ct?"A":"B"}function o0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function wo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Co(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function jb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var rf=50,A2=15,R2=50,M2=500,D2=" ",B2=new RegExp(D2,"g"),up=class extends ft{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new 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 j2(this._bufferService),this._activeSelectionMode=0,this._register(ti(()=>{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(B2," ")).join(r0?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Yp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=jb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Gp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-rf),rf),t/=rf,t/Math.abs(t)+Math.round(t*(A2-1)))}shouldForceSelection(e){return Eu?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),R2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Eu&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,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+=z-1,p+=z-1);j>0&&h>0&&!this._isCharWordSeparator(o.loadCell(j-1,this._workCell));){o.loadCell(j-1,this._workCell);let O=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,j--):O>1&&(b+=O-1,h-=O-1),h--,j--}for(;E1&&(v+=O-1,p+=O-1),p++,E++}}p++;let y=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&y===0&&o.getCodePoint(0)!==32){let j=a.lines.get(e[1]-1);if(j&&o.isWrapped&&j.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let z=this._bufferService.cols-E.start;y-=z,N+=z}}}if(s&&y+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let j=a.lines.get(e[1]+1);if(j!=null&&j.isWrapped&&j.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:y,length:N}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=jb(i,this._bufferService.cols)}};up=fi([Re(3,mn),Re(4,ca),Re(5,Ip),Re(6,gn),Re(7,Jr),Re(8,Qr)],up);var Ab=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Rb=class{constructor(){this._color=new Ab,this._css=new Ab}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[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:ki.toCss(s,a,o),rgba:ki.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:ki.toCss(s,s,s),rgba:ki.toRgba(s,s,s)})}return e})()),ia=ai.toColor("#ffffff"),mo=ai.toColor("#000000"),Mb=ai.toColor("#ffffff"),Db=mo,so={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},L2=ia,hp=class extends ft{constructor(e){super(),this._optionsService=e,this._contrastCache=new Rb,this._halfContrastCache=new Rb,this._onChangeColors=this._register(new we),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ia,background:mo,cursor:Mb,cursorAccent:Db,selectionForeground:void 0,selectionBackgroundTransparent:so,selectionBackgroundOpaque:Qt.blend(mo,so),selectionInactiveBackgroundTransparent:so,selectionInactiveBackgroundOpaque:Qt.blend(mo,so),scrollbarSliderBackground:Qt.opacity(ia,.2),scrollbarSliderHoverBackground:Qt.opacity(ia,.4),scrollbarSliderActiveBackground:Qt.opacity(ia,.5),overviewRulerBorder:ia,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Ft(e.foreground,ia),t.background=Ft(e.background,mo),t.cursor=Qt.blend(t.background,Ft(e.cursor,Mb)),t.cursorAccent=Qt.blend(t.background,Ft(e.cursorAccent,Db)),t.selectionBackgroundTransparent=Ft(e.selectionBackground,so),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Ft(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Ft(e.selectionForeground,Eb):void 0,t.selectionForeground===Eb&&(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=Ft(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Ft(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Ft(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=Ft(e.overviewRulerBorder,L2),t.ansi=Ti.slice(),t.ansi[0]=Ft(e.black,Ti[0]),t.ansi[1]=Ft(e.red,Ti[1]),t.ansi[2]=Ft(e.green,Ti[2]),t.ansi[3]=Ft(e.yellow,Ti[3]),t.ansi[4]=Ft(e.blue,Ti[4]),t.ansi[5]=Ft(e.magenta,Ti[5]),t.ansi[6]=Ft(e.cyan,Ti[6]),t.ansi[7]=Ft(e.white,Ti[7]),t.ansi[8]=Ft(e.brightBlack,Ti[8]),t.ansi[9]=Ft(e.brightRed,Ti[9]),t.ansi[10]=Ft(e.brightGreen,Ti[10]),t.ansi[11]=Ft(e.brightYellow,Ti[11]),t.ansi[12]=Ft(e.brightBlue,Ti[12]),t.ansi[13]=Ft(e.brightMagenta,Ti[13]),t.ansi[14]=Ft(e.brightCyan,Ti[14]),t.ansi[15]=Ft(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)}},P2={trace:0,debug:1,info:2,warn:3,error:4,off:5},I2="xterm.js: ",dp=class extends ft{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=P2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*dt+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*dt+0]=t|2097152|i[2]<<22):this._data[t*dt+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*dt+0]>>22}hasWidth(t){return this._data[t*dt+0]&12582912}getFg(t){return this._data[t*dt+1]}getBg(t){return this._data[t*dt+2]}hasContent(t){return this._data[t*dt+0]&4194303}getCodePoint(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*dt+0]&2097152}getString(t){let i=this._data[t*dt+0];return i&2097152?this._combined[t]:i&2097151?js(i&2097151):""}isProtected(t){return this._data[t*dt+2]&536870912}loadCell(t,i){return Jc=t*dt,i.content=this._data[Jc+0],i.fg=this._data[Jc+1],i.bg=this._data[Jc+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*dt+0]=i.content,this._data[t*dt+1]=i.fg,this._data[t*dt+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*dt+0]=i|s<<22,this._data[t*dt+1]=a.fg,this._data[t*dt+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*dt+0];a&2097152?this._combined[t]+=js(i):a&2097151?(this._combined[t]=js(a&2097151)+js(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*dt+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*sf=0;--t)if(this._data[t*dt+0]&4194303)return t+(this._data[t*dt+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*dt+0]&4194303||this._data[t*dt+2]&50331648)return t+(this._data[t*dt+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let 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 H2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(j>x||_[j].getTrimmedLength()===0);j--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function U2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cko(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 ko(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var u0=class h0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=h0._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(),aa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};u0._nextId=1;var q2=u0,Ri={},na=Ri.B;Ri[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Ri.A={"#":"£"};Ri.B=void 0;Ri[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Ri.C=Ri[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Ri.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Ri.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Ri.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Ri.E=Ri[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Ri.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Ri.H=Ri[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Ri["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Lb=4294967295,Ob=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ci.clone(),this.savedCharset=na,this.markers=[],this._nullCell=lr.fromCharData([0,Ty,1,0]),this._whitespaceCell=lr.fromCharData([0,Rs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Nu,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new wu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new wu),this._whitespaceCell}getBlankLine(e,t){return new go(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eLb?Lb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ci);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ci),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new go(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=H2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ci),i);if(s.length>0){let a=U2(this.lines,s);$2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ci),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let O=this.ybase+this.y;if(O>=c&&O0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let y=_.length-1,N=_[y];N===0&&(y--,N=_[y]);let j=p.length-x-1,E=f;for(;j>=0;){let O=Math.min(E,N);if(p[y]===void 0)break;if(p[y].copyCellsFrom(p[j],E-O,N-O,O,!0),N-=O,N===0&&(y--,N=_[y]),E-=O,E===0){j--;let W=Math.max(j,0);E=ko(p,W,this._cols)}}for(let O=0;O0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let j=x.newLines.length-1;j>=0;j--)this.lines.set(N--,x.newLines[j]);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 y=Math.max(0,p+o-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},W2=class extends ft{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 Ob(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ob(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},d0=2,f0=1,fp=class extends ft{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,d0),this.rows=Math.max(e.rawOptions.rows||0,f0),this.buffers=this._register(new W2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};fp=fi([Re(0,gn)],fp);var Va={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Eu,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},G2=["normal","bold","100","200","300","400","500","600","700","800","900"],Y2=class extends ft{constructor(e){super(),this._onOptionChange=this._register(new we),this.onOptionChange=this._onOptionChange.event;let t={...Va};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ti(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Va))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Va[e]),!K2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Va[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=G2.includes(t)?t:Va[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function K2(e){return e==="block"||e==="underline"||e==="bar"}function xo(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&xo(e[s],t-1);return i}var zb=Object.freeze({insertMode:!1}),Pb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new 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=xo(zb),this.decPrivateModes=xo(Pb)}reset(){this.modes=xo(zb),this.decPrivateModes=xo(Pb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pp=fi([Re(0,mn),Re(1,Dy),Re(2,gn)],pp);var Ib={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function af(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var lf=String.fromCharCode,Hb={DEFAULT:e=>{let t=[af(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${lf(t[0])}${lf(t[1])}${lf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${af(e,!0)};${e.x};${e.y}${t}`}},mp=class extends ft{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new we),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Ib))this.addProtocol(s,Ib[s]);for(let s of Object.keys(Hb))this.addEncoding(s,Hb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mp=fi([Re(0,mn),Re(1,ca),Re(2,gn)],mp);var of=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],V2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],ji;function X2(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ra.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ra.createPropertyValue(0,i,s)}},ra=class gu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new we,this.onChange=this._onChange.event;let t=new Z2;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=gu.extractWidth(h);gu.extractShouldJoin(h)&&(p-=gu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},Q2=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ub(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ao=2147483647,J2=256,p0=class gp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>J2)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new gp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ao?ao:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>ao?ao:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,ao):t}},lo=[],eE=class{constructor(){this._state=0,this._active=lo,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=lo}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=lo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lo,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=lo,this._id=-1,this._state=0}}},Hn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},oo=[],tE=class{constructor(){this._handlers=Object.create(null),this._active=oo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=oo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=oo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||oo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Bu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=oo,this._ident=0}},_o=new p0;_o.addParam(0);var $b=class{constructor(e){this._handler=e,this._data="",this._params=_o,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_o,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Bu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=_o,this._data="",this._hitLimit=!1,i));return this._params=_o,this._data="",this._hitLimit=!1,t}},iE=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})(),rE=class extends ft{constructor(e=nE){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 p0,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(ti(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new eE),this._dcsParser=this._register(new tE),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 cf(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function lE(e,t=16){let[i,s,a]=e;return`rgb:${cf(i,t)}/${cf(s,t)}/${cf(a,t)}`}var oE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ns=131072,qb=10;function Wb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Gb=5e3,Yb=0,cE=class extends ft{constructor(e,t,i,s,a,o,c,h,p=new rE){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 TC,this._utf8Decoder=new jC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ci.clone(),this._eraseAttrDataInternal=Ci.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 xp(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(pu.IND,()=>this.index()),this._parser.setExecuteHandler(pu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(pu.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 Ri)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 $b((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"),Gb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Gb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ns&&(o=this._parseStack.position+Ns)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,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.lengthNs)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,z=this._activeBuffer.x-j;for(this._activeBuffer.x=j,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),j>0&&x instanceof go&&x.copyCellsFrom(E,z,0,j,!1);z=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-j,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Wb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new $b(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Hn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let 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,j)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${j}$y`),!0),v=N=>N?1:2,y=e.params[0];return t?y===2?b(y,4):y===4?b(y,v(c.modes.insertMode)):y===12?b(y,3):y===20?b(y,v(x.convertEol)):b(y,0):y===1?b(y,v(s.applicationCursorKeys)):y===3?b(y,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):y===6?b(y,v(s.origin)):y===7?b(y,v(s.wraparound)):y===8?b(y,3):y===9?b(y,v(a==="X10")):y===12?b(y,v(x.cursorBlink)):y===25?b(y,v(!c.isCursorHidden)):y===45?b(y,v(s.reverseWraparound)):y===66?b(y,v(s.applicationKeypad)):y===67?b(y,4):y===1e3?b(y,v(a==="VT200")):y===1002?b(y,v(a==="DRAG")):y===1003?b(y,v(a==="ANY")):y===1004?b(y,v(s.sendFocus)):y===1005?b(y,4):y===1006?b(y,v(o==="SGR")):y===1015?b(y,4):y===1016?b(y,v(o==="SGR_PIXELS")):y===1048?b(y,1):y===47||y===1047||y===1049?b(y,v(f===_)):y===2004?b(y,v(s.bracketedPasteMode)):y===2026?b(y,v(s.synchronizedOutput)):b(y,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ao.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ci.fg,e.bg=Ci.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|=Ci.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ci.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|=Ci.fg&16777215,s.bg&=-67108864,s.bg|=Ci.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=Ci.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Wb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>qb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>qb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Kb(o))if(a==="?")t.push({type:0,index:o});else{let c=Fb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Fb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Ci.clone(),this._eraseAttrDataInternal=Ci.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(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},xp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Yb=e,e=t,t=Yb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};xp=fi([Re(0,mn)],xp);function Kb(e){return 0<=e&&e<256}var uE=5e7,Vb=12,hE=50,dE=class extends ft{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new 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>uE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=Vb?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Vb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>hE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},_p=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};_p=fi([Re(0,mn)],_p);var Xb=!1,fE=class extends ft{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new sl),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 z2,this.optionsService=this._register(new Y2(e)),this._instantiationService.setService(gn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fp)),this._instantiationService.setService(mn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(dp)),this._instantiationService.setService(Dy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pp)),this._instantiationService.setService(ca,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(My,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ra)),this._instantiationService.setService(DC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Q2),this._instantiationService.setService(MC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_p),this._instantiationService.setService(By,this._oscLinkService),this._inputHandler=this._register(new cE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Zi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Zi.forward(this._bufferService.onResize,this._onResize)),this._register(Zi.forward(this.coreService.onData,this._onData)),this._register(Zi.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 dE((t,i)=>this._inputHandler.parse(t,i))),this._register(Zi.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&&!Xb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Xb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,d0),t=Math.max(t,f0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ub.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ub(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ti(()=>{for(let t of e)t.dispose()})}}},pE={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 mE(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=pE[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 xi=0,gE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Nu,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Nu,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(xi=this._search(t),xi===-1)||this._getKey(this._array[xi])!==t)return!1;do if(this._array[xi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(xi),!0;while(++xia-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&&(xi=this._search(e),!(xi<0||xi>=this._array.length)&&this._getKey(this._array[xi])===e))do yield this._array[xi];while(++xi=this._array.length)&&this._getKey(this._array[xi])===e))do t(this._array[xi]);while(++xi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},uf=0,Zb=0,xE=class extends ft{constructor(){super(),this._decorations=new gE(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(ti(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new _E(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{uf=a.options.x??0,Zb=uf+(a.options.width??1),e>=uf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Qb=20,Tu=class extends ft{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new vE(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(ti(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Qb+1&&(this._liveRegion.textContent+=Pf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),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;aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(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&&yE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,aa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};bp=fi([Re(1,Ip),Re(2,Jr),Re(3,mn),Re(4,Oy)],bp);function yE(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 SE=class extends fE{constructor(e={}){super(e),this._linkifier=this._register(new sl),this.browser=t0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new sl),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(xE),this._instantiationService.setService(Ro,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(h2),this._instantiationService.setService(Oy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Hf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Zi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Zi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Zi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Zi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ti(()=>{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(`${pe.ESC}]${s};${lE(a)}${Jy.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=ki.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=ki.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ke(this.element,"copy",t=>{this.hasSelection()&&EC(t,this._selectionService)}));let e=t=>NC(t,this.textarea,this.coreService,this.optionsService);this._register(Ke(this.textarea,"paste",e)),this._register(Ke(this.element,"paste",e)),i0?this._register(Ke(this.element,"mousedown",t=>{t.button===2&&ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ke(this.element,"contextmenu",t=>{ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Yp&&this._register(Ke(this.element,"auxclick",t=>{t.button===1&&Ny(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",zf.get()),s0||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(c2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Qr,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(lp,this._document,this._helperContainer),this._instantiationService.setService(Lu,this._charSizeService),this._themeService=this._instantiationService.createInstance(hp),this._instantiationService.setService(ol,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ku),this._instantiationService.setService(Ly,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cp,this.rows,this.screenElement)),this._instantiationService.setService(Jr,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(rp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(op),this._instantiationService.setService(Ip,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(bp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ip,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(up,this.element,this.screenElement,s)),this._instantiationService.setService(LC,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(Zi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(np,this.screenElement)),this._register(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(Tu,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ap,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var 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 y=o.deltaY;if(y===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=y<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(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){Ey(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=mE(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)&&(wE(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)}},Jb=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new kE(t)}getNullCell(){return new lr}},EE=class extends ft{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new we),this.onBufferChange=this._onBufferChange.event,this._normal=new Jb(this._core.buffers.normal,"normal"),this._alternate=new Jb(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},NE=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)}},TE=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}},jE=["cols","rows"],Sr=0,AE=class extends ft{constructor(e){super(),this._core=this._register(new SE(e)),this._addonManager=this._register(new CE),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(jE.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 NE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new TE(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 EE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return zf.get()},set promptLabel(e){zf.set(e)},get tooMuchOutput(){return Pf.get()},set tooMuchOutput(e){Pf.set(e)}}}_verifyIntegers(...e){for(Sr of e)if(Sr===1/0||isNaN(Sr)||Sr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Sr of e)if(Sr&&(Sr===1/0||isNaN(Sr)||Sr%1!==0||Sr<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 RE=2,ME=1,DE=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(RE,Math.floor(_/e.css.cell.width)),rows:Math.max(ME,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 Pi=0,Ii=0,Hi=0,di=0,rn;(e=>{function t(a,o,c,h){return h!==void 0?`#${Js(a)}${Js(o)}${Js(c)}${Js(h)}`:`#${Js(a)}${Js(o)}${Js(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(rn||(rn={}));var BE;(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,y=p.rgba>>16&255,N=p.rgba>>8&255;Pi=v+Math.round((_-v)*di),Ii=y+Math.round((x-y)*di),Hi=N+Math.round((b-N)*di);let j=rn.toCss(Pi,Ii,Hi),E=rn.toRgba(Pi,Ii,Hi);return{css:j,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 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]=xu.toChannels(f),{css:rn.toCss(Pi,Ii,Hi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[Pi,Ii,Hi]=xu.toChannels(p.rgba),{css:rn.toCss(Pi,Ii,Hi,di),rgba:rn.toRgba(Pi,Ii,Hi,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})(BE||(BE={}));var Vi;(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),di=parseInt(a.slice(4,5).repeat(2),16),rn.toColor(Pi,Ii,Hi,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 Pi=parseInt(o[1]),Ii=parseInt(o[2]),Hi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),rn.toColor(Pi,Ii,Hi,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),[Pi,Ii,Hi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rn.toRgba(Pi,Ii,Hi,di),css:a}}e.toColor=s})(Vi||(Vi={}));var fn;(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})(fn||(fn={}));var xu;(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 Pi=x+Math.round((p-x)*di),Ii=b+Math.round((f-b)*di),Hi=v+Math.round((_-v)*di),rn.toRgba(Pi,Ii,Hi)}e.blend=t;function i(c,h,p){let f=fn.relativeLuminance(c>>8),_=fn.relativeLuminance(h>>8);if(Kr(f,_)>8));if(y>8));return y>j?v:N}return v}let x=a(c,h,p),b=Kr(f,fn.relativeLuminance(x>>8));if(b>8));return b>y?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,y=h>>8&255,N=Kr(fn.relativeLuminance2(b,v,y),fn.relativeLuminance2(f,_,x));for(;N0||v>0||y>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),y-=Math.max(0,Math.ceil(y*.1)),N=Kr(fn.relativeLuminance2(b,v,y),fn.relativeLuminance2(f,_,x));return(b<<24|v<<16|y<<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,y=h>>8&255,N=Kr(fn.relativeLuminance2(b,v,y),fn.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 Js(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Kr(e,t){return e{let e=[Vi.toColor("#2e3436"),Vi.toColor("#cc0000"),Vi.toColor("#4e9a06"),Vi.toColor("#c4a000"),Vi.toColor("#3465a4"),Vi.toColor("#75507b"),Vi.toColor("#06989a"),Vi.toColor("#d3d7cf"),Vi.toColor("#555753"),Vi.toColor("#ef2929"),Vi.toColor("#8ae234"),Vi.toColor("#fce94f"),Vi.toColor("#729fcf"),Vi.toColor("#ad7fa8"),Vi.toColor("#34e2e2"),Vi.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 ev(e,t,i){return Math.max(t,Math.min(e,i))}function OE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var m0=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&&!Vr(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r +`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&Vr(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&Vr(c,p)&&Vr(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!g0(e,t),a=!Vr(e,t),o=!x0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!Vr(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(Vr(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{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}},PE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:ev(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new zE(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 IE(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:ev(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(){}},IE=class extends m0{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=LE}_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=!g0(e,t),a=!Vr(e,t),o=!x0(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+=OE(e.getChars())}_serializeString(){return this._htmlContent}};const HE="__OWS_FRESH_SESSION__",Xa="[REDACTED]",UE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${Xa}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${Xa}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${Xa}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${Xa}`]];function tv(e){let t=e;for(const[i,s]of UE)t=t.replace(i,s);return t}const iv="codex features enable image_generation";function $E(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const FE={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"},qE="plotlink-terminal",WE=1,Ds="scrollback",nv=10*1024*1024;function Kp(){return new Promise((e,t)=>{const i=indexedDB.open(qE,WE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Ds)||s.createObjectStore(Ds)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function Za(e,t){const i=t.length>nv?t.slice(-nv):t,s=await Kp();return new Promise((a,o)=>{const c=s.transaction(Ds,"readwrite");c.objectStore(Ds).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function GE(e){const t=await Kp();return new Promise((i,s)=>{const o=t.transaction(Ds,"readonly").objectStore(Ds).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function hf(e){const t=await Kp();return new Promise((i,s)=>{const a=t.transaction(Ds,"readwrite");a.objectStore(Ds).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ai=new Map;function YE({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 y=w.useRef(null),N=w.useRef(i),[j,E]=w.useState([]),[z,O]=w.useState(new Set),[W,q]=w.useState(null),[D,te]=w.useState(null),[de,_e]=w.useState(!1),[P,ae]=w.useState(!1),G=$E(x,_),Y=!!b,Q=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const I=w.useCallback($=>{var be;const{width:le}=$.container.getBoundingClientRect();if(!(le<50))try{$.fit.fit(),((be=$.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&$.ws.send(JSON.stringify({type:"resize",cols:$.term.cols,rows:$.term.rows}))}catch{}},[]),A=w.useCallback($=>{for(const[le,be]of Ai)be.container.style.display=le===$?"block":"none";if($){const le=Ai.get($);le&&setTimeout(()=>I(le),50)}},[I]),B=w.useRef({});w.useEffect(()=>{B.current=p||{}},[p]);const U=w.useRef({});w.useEffect(()=>{U.current=f||{}},[f]);const ge=w.useCallback(($,le,be)=>{const Te=window.location.protocol==="https:"?"wss:":"ws:",Le=B.current[$]?"&bypass=true":"",ze=U.current[$],ye=ze?`&provider=${encodeURIComponent(ze)}`:"",rt=new WebSocket(`${Te}//${window.location.host}/ws/terminal?story=${encodeURIComponent($)}&token=${e}&resume=${be}${Le}${ye}`);rt.onopen=()=>{le.connected=!0,le._retried=!1,O(wt=>{const vt=new Set(wt);return vt.delete($),vt}),rt.send(JSON.stringify({type:"resize",cols:le.term.cols,rows:le.term.rows}))};let bt=!0;rt.onmessage=wt=>{if(bt&&(bt=!1,typeof wt.data=="string"&&wt.data===HE)){le.term.reset(),hf($).catch(()=>{});return}le.term.write(typeof wt.data=="string"?tv(wt.data):wt.data)},rt.onclose=wt=>{if(le.connected=!1,le.ws===rt){le.ws=null;try{const vt=le.serialize.serialize();Za($,vt).catch(()=>{})}catch{}if(wt.code===4e3&&!le._retried){le._retried=!0,le.term.write(`\r +\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r +`),Q.current($,le,!1);return}O(vt=>new Set(vt).add($))}},le.term.onData(wt=>{rt.readyState===WebSocket.OPEN&&rt.send(wt)}),le.ws=rt},[e]);w.useEffect(()=>{Q.current=ge},[ge]);const T=w.useCallback(async($,le)=>{if(!y.current||Ai.has($))return;const{resume:be=!1,autoConnect:Te=!0}=le??{},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",y.current.appendChild(Le);const ze=new AE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:FE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),ye=new DE,rt=new PE;ze.loadAddon(ye),ze.loadAddon(rt),ze.open(Le);const bt={term:ze,fit:ye,serialize:rt,ws:null,container:Le,observer:null,connected:!1},wt=new ResizeObserver(()=>{var Ve;const{width:vt}=Le.getBoundingClientRect();if(!(vt<50))try{ye.fit(),((Ve=bt.ws)==null?void 0:Ve.readyState)===WebSocket.OPEN&&bt.ws.send(JSON.stringify({type:"resize",cols:ze.cols,rows:ze.rows}))}catch{}});wt.observe(Le),bt.observer=wt,Ai.set($,bt),E(vt=>[...vt,$]);try{const vt=await GE($);if(vt){const Ve=tv(vt);ze.write(Ve),Ve!==vt&&Za($,Ve).catch(()=>{})}}catch{}Te?ge($,bt,be):O(vt=>new Set(vt).add($)),setTimeout(()=>I(bt),50)},[ge,I]),R=w.useCallback(async($,le)=>{const be=Ai.get($);be&&(be.ws&&(be.ws.close(),be.ws=null),le||(await N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),be.term.clear()),ge($,be,le))},[ge]),V=w.useCallback($=>{const le=Ai.get($);if(le){try{const be=le.serialize.serialize();Za($,be).catch(()=>{})}catch{}le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),Ai.delete($),E(be=>be.filter(Te=>Te!==$)),O(be=>{const Te=new Set(be);return Te.delete($),Te}),i(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{}),a==null||a($)}},[i,a]),C=w.useCallback($=>{var be;const le=Ai.get($);le&&(((be=le.ws)==null?void 0:be.readyState)===WebSocket.OPEN&&le.ws.send(`exit +`),hf($).catch(()=>{}),le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),Ai.delete($),E(Te=>Te.filter(Le=>Le!==$)),O(Te=>{const Le=new Set(Te);return Le.delete($),Le}),i(`/api/terminal/${encodeURIComponent($)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a($))},[i,a]),K=w.useCallback(async($,le,be)=>{const Te=Ai.get($);if(!Te||Ai.has(le)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:$,newName:le,...be??{}})})).ok)return!1;Ai.delete($),Ai.set(le,Te);try{const ze=Te.serialize.serialize();await hf($),await Za(le,ze)}catch{}return E(ze=>ze.map(ye=>ye===$?le:ye)),O(ze=>{if(!ze.has($))return ze;const ye=new Set(ze);return ye.delete($),ye.add(le),ye}),(Te.connected||Te.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(le)}`,{method:"DELETE"}).catch(()=>{}),Te.ws&&(Te.ws.close(),Te.ws=null),Q.current(le,Te,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=K),()=>{h&&(h.current=null)}),[h,K]),w.useEffect(()=>{if(t){if(G){A(null);return}if(Y){A(null);return}Ai.has(t)?A(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then($=>$.ok?$.json():null).then($=>{if(!Ai.has(t)){const le=($==null?void 0:$.sessionId)&&!($!=null&&$.running);T(t,{autoConnect:!le}),A(t)}}).catch(()=>{Ai.has(t)||(T(t),A(t))})}},[t,T,A,G,Y]),w.useEffect(()=>{const $=setInterval(()=>{for(const[le,be]of Ai)if(be.connected)try{const Te=be.serialize.serialize();Za(le,Te).catch(()=>{})}catch{}},3e4);return()=>clearInterval($)},[]),w.useEffect(()=>()=>{for(const[$,le]of Ai){try{const be=le.serialize.serialize();Za($,be).catch(()=>{})}catch{}le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),N.current(`/api/terminal/${encodeURIComponent($)}`,{method:"DELETE"}).catch(()=>{})}Ai.clear()},[]);const re=t?z.has(t):!1,ue=j.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!ue&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[j.map($=>d.jsxs("div",{onClick:()=>s==null?void 0:s($),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${$===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z.has($)?"bg-amber-500":$===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${$.startsWith("_new_")?"italic":""}`,children:$.startsWith("_new_")?"Untitled":$}),d.jsx("button",{onClick:le=>{le.stopPropagation(),$.startsWith("_new_")?q($):V($)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},$)),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:()=>te(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:y,className:"h-full"}),ue&&!G&&!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"})]})}),G&&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."]}):Su(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[zp," 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:iv}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(iv),_e(!0),setTimeout(()=>_e(!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:de?"Copied!":"Copy"})]})]})]})}),Y&&!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:P,onClick:async()=>{if(!P){ae(!0);try{await(v==null?void 0:v())}finally{ae(!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:P?"Setting…":"Set this story's provider to Codex"})]})}),W&&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 $=W;q(null),C($)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),D&&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:()=>te(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const $=D;te(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$})})).ok&&(V($),o==null||o($))}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:()=>R(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:()=>R(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 KE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const VE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,XE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,ZE={};function rv(e,t){return(ZE.jsx?XE:VE).test(e)}const QE=/[ \t\n\f\r]/g;function JE(e){return typeof e=="object"?e.type==="text"?sv(e.value):!1:sv(e)}function sv(e){return e.replace(QE,"")===""}class Bo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Bo.prototype.normal={};Bo.prototype.property={};Bo.prototype.space=void 0;function _0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Bo(i,s,t)}function vp(e){return e.toLowerCase()}class 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 eN=0;const lt=ua(),wi=ua(),yp=ua(),ve=ua(),Yt=ua(),il=ua(),Un=ua();function ua(){return 2**++eN}const Sp=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:wi,commaOrSpaceSeparated:Un,commaSeparated:il,number:ve,overloadedBoolean:yp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),df=Object.keys(Sp);class Vp extends Tn{constructor(t,i,s,a){let o=-1;if(super(t,i),av(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&sN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(lv,oN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!lv.test(o)){let c=o.replace(rN,lN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Vp}return new a(s,t)}function lN(e){return"-"+e.toLowerCase()}function oN(e){return e.charAt(1).toUpperCase()}const cN=_0([b0,tN,S0,w0,C0],"html"),Xp=_0([b0,iN,S0,w0,C0],"svg");function uN(e){return e.join(" ").trim()}var Qa={},ff,ov;function hN(){if(ov)return ff;ov=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` +`,f="/",_="*",x="",b="comment",v="declaration";function y(j,E){if(typeof j!="string")throw new TypeError("First argument must be a string");if(!j)return[];E=E||{};var z=1,O=1;function W(Q){var I=Q.match(t);I&&(z+=I.length);var A=Q.lastIndexOf(p);O=~A?Q.length-A:O+Q.length}function q(){var Q={line:z,column:O};return function(I){return I.position=new D(Q),_e(),I}}function D(Q){this.start=Q,this.end={line:z,column:O},this.source=E.source}D.prototype.content=j;function te(Q){var I=new Error(E.source+":"+z+":"+O+": "+Q);if(I.reason=Q,I.filename=E.source,I.line=z,I.column=O,I.source=j,!E.silent)throw I}function de(Q){var I=Q.exec(j);if(I){var A=I[0];return W(A),j=j.slice(A.length),I}}function _e(){de(i)}function P(Q){var I;for(Q=Q||[];I=ae();)I!==!1&&Q.push(I);return Q}function ae(){var Q=q();if(!(f!=j.charAt(0)||_!=j.charAt(1))){for(var I=2;x!=j.charAt(I)&&(_!=j.charAt(I)||f!=j.charAt(I+1));)++I;if(I+=2,x===j.charAt(I-1))return te("End of comment missing");var A=j.slice(2,I-2);return O+=2,W(A),j=j.slice(I),O+=2,Q({type:b,comment:A})}}function G(){var Q=q(),I=de(s);if(I){if(ae(),!de(a))return te("property missing ':'");var A=de(o),B=Q({type:v,property:N(I[0].replace(e,x)),value:A?N(A[0].replace(e,x)):x});return de(c),B}}function Y(){var Q=[];P(Q);for(var I;I=G();)I!==!1&&(Q.push(I),P(Q));return Q}return _e(),Y()}function N(j){return j?j.replace(h,x):x}return ff=y,ff}var cv;function dN(){if(cv)return Qa;cv=1;var e=Qa&&Qa.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.default=i;const t=e(hN());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 Qa}var co={},uv;function fN(){if(uv)return co;uv=1,Object.defineProperty(co,"__esModule",{value:!0}),co.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(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 co.camelCase=p,co}var uo,hv;function pN(){if(hv)return uo;hv=1;var e=uo&&uo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(dN()),i=fN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,uo=s,uo}var mN=pN();const gN=Du(mN),k0=E0("end"),Zp=E0("start");function E0(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 N0(e){const t=Zp(e),i=k0(e);if(t&&i)return{start:t,end:i}}function vo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?dv(e.position):"start"in e||"end"in e?dv(e):"line"in e||"column"in e?wp(e):""}function wp(e){return fv(e&&e.line)+":"+fv(e&&e.column)}function dv(e){return wp(e&&e.start)+"-"+wp(e&&e.end)}function fv(e){return e&&typeof e=="number"?e:1}class 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=vo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}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 Qp={}.hasOwnProperty,xN=new Map,_N=/[A-Z]/g,bN=new Set(["table","tbody","thead","tfoot","tr"]),vN=new Set(["td","th"]),T0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function yN(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=jN(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=TN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Xp:cN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=j0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function j0(e,t,i){if(t.type==="element")return SN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return wN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return kN(e,t,i);if(t.type==="mdxjsEsm")return CN(e,t);if(t.type==="root")return EN(e,t,i);if(t.type==="text")return NN(e,t)}function SN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=R0(e,t.tagName,!1),c=AN(e,t);let h=em(e,t);return bN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!JE(p):!0})),A0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function wN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Eo(e,t.position)}function CN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Eo(e,t.position)}function kN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=Xp,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:R0(e,t.name,!0),c=RN(e,t),h=em(e,t);return A0(e,c,o,t),Jp(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function EN(e,t,i){const s={};return Jp(s,em(e,t)),e.create(t,e.Fragment,s,i)}function NN(e,t){return t.value}function A0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function Jp(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function TN(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 jN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=Zp(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function AN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&Qp.call(t.properties,a)){const o=MN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&vN.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 RN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Eo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Eo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function em(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:xN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?($n(e,e.length,0,t),e):t}const gv={}.hasOwnProperty;function D0(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 gr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const pn=Bs(/[A-Za-z]/),sn=Bs(/[\dA-Za-z]/),UN=Bs(/[#-'*+\--9=?A-Z^-~]/);function ju(e){return e!==null&&(e<32||e===127)}const Cp=Bs(/\d/),$N=Bs(/[\dA-Fa-f]/),FN=Bs(/[!-/:-@[-`{-~]/);function Fe(e){return e!==null&&e<-2}function Gt(e){return e!==null&&(e<0||e===32)}function _t(e){return e===-2||e===-1||e===32}const Pu=Bs(new RegExp("\\p{P}|\\p{S}","u")),oa=Bs(/\s/);function Bs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function hl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function Nt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return _t(p)?(e.enter(i),h(p)):t(p)}function h(p){return _t(p)&&o++c))return;const te=t.events.length;let de=te,_e,P;for(;de--;)if(t.events[de][0]==="exit"&&t.events[de][1].type==="chunkFlow"){if(_e){P=t.events[de][1].end;break}_e=!0}for(E(s),D=te;DO;){const q=i[W];t.containerState=q[1],q[0].exit.call(t,e)}i.length=O}function z(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function KN(e,t,i){return Nt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function al(e){if(e===null||Gt(e)||oa(e))return 1;if(Pu(e))return 2}function Iu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};_v(x,-p),_v(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},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,Iu(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,$n(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&_t(D)?Nt(e,z,"linePrefix",o+1)(D):z(D)}function z(D){return D===null||Fe(D)?e.check(bv,N,W)(D):(e.enter("codeFlowValue"),O(D))}function O(D){return D===null||Fe(D)?(e.exit("codeFlowValue"),z(D)):(e.consume(D),O)}function W(D){return e.exit("codeFenced"),t(D)}function q(D,te,de){let _e=0;return P;function P(I){return D.enter("lineEnding"),D.consume(I),D.exit("lineEnding"),ae}function ae(I){return D.enter("codeFencedFence"),_t(I)?Nt(D,G,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):G(I)}function G(I){return I===h?(D.enter("codeFencedFenceSequence"),Y(I)):de(I)}function Y(I){return I===h?(_e++,D.consume(I),Y):_e>=c?(D.exit("codeFencedFenceSequence"),_t(I)?Nt(D,Q,"whitespace")(I):Q(I)):de(I)}function Q(I){return I===null||Fe(I)?(D.exit("codeFencedFence"),te(I)):de(I)}}}function a5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const mf={name:"codeIndented",tokenize:o5},l5={partial:!0,tokenize:c5};function o5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),Nt(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):Fe(f)?e.attempt(l5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Fe(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function c5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Fe(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):Nt(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):Fe(c)?a(c):i(c)}}const u5={name:"codeText",previous:d5,resolve:h5,tokenize:f5};function h5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&ho(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ho(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function I0(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||ju(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),N(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Fe(E)?i(E):(e.consume(E),E===92?y:v)}function y(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||Gt(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):Fe(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||Fe(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!_t(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function U0(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):Fe(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),Nt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Fe(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 yo(e,t){let i;return s;function s(a){return Fe(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):_t(a)?Nt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const y5={name:"definition",tokenize:w5},S5={partial:!0,tokenize:C5};function w5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return H0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=gr(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 Gt(v)?yo(e,f)(v):f(v)}function f(v){return I0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(S5,x,x)(v)}function x(v){return _t(v)?Nt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Fe(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function C5(e,t,i){return s;function s(h){return Gt(h)?yo(e,a)(h):i(h)}function a(h){return U0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return _t(h)?Nt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Fe(h)?t(h):i(h)}}const k5={name:"hardBreakEscape",tokenize:E5};function E5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Fe(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const N5={name:"headingAtx",resolve:T5,tokenize:j5};function T5(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 j5(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||Gt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Fe(_)?(e.exit("atxHeading"),t(_)):_t(_)?Nt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Gt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const A5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],yv=["pre","script","style","textarea"],R5={concrete:!0,name:"htmlFlow",resolveTo:B5,tokenize:L5},M5={partial:!0,tokenize:z5},D5={partial:!0,tokenize:O5};function B5(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 L5(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):pn(C)?(e.consume(C),c=String.fromCharCode(C),j):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,y):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 y(C){const K="CDATA[";return C===K.charCodeAt(h++)?(e.consume(C),h===K.length?s.interrupt?t:G:y):i(C)}function N(C){return pn(C)?(e.consume(C),c=String.fromCharCode(C),j):i(C)}function j(C){if(C===null||C===47||C===62||Gt(C)){const K=C===47,re=c.toLowerCase();return!K&&!o&&yv.includes(re)?(a=1,s.interrupt?t(C):G(C)):A5.includes(c.toLowerCase())?(a=6,K?(e.consume(C),E):s.interrupt?t(C):G(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?z(C):O(C))}return C===45||sn(C)?(e.consume(C),c+=String.fromCharCode(C),j):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:G):i(C)}function z(C){return _t(C)?(e.consume(C),z):P(C)}function O(C){return C===47?(e.consume(C),P):C===58||C===95||pn(C)?(e.consume(C),W):_t(C)?(e.consume(C),O):P(C)}function W(C){return C===45||C===46||C===58||C===95||sn(C)?(e.consume(C),W):q(C)}function q(C){return C===61?(e.consume(C),D):_t(C)?(e.consume(C),q):O(C)}function D(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,te):_t(C)?(e.consume(C),D):de(C)}function te(C){return C===p?(e.consume(C),p=null,_e):C===null||Fe(C)?i(C):(e.consume(C),te)}function de(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Gt(C)?q(C):(e.consume(C),de)}function _e(C){return C===47||C===62||_t(C)?O(C):i(C)}function P(C){return C===62?(e.consume(C),ae):i(C)}function ae(C){return C===null||Fe(C)?G(C):_t(C)?(e.consume(C),ae):i(C)}function G(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),B):C===62&&a===4?(e.consume(C),R):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),ge):Fe(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(M5,V,Y)(C)):C===null||Fe(C)?(e.exit("htmlFlowData"),Y(C)):(e.consume(C),G)}function Y(C){return e.check(D5,Q,V)(C)}function Q(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),I}function I(C){return C===null||Fe(C)?Y(C):(e.enter("htmlFlowData"),G(C))}function A(C){return C===45?(e.consume(C),T):G(C)}function B(C){return C===47?(e.consume(C),c="",U):G(C)}function U(C){if(C===62){const K=c.toLowerCase();return yv.includes(K)?(e.consume(C),R):G(C)}return pn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),U):G(C)}function ge(C){return C===93?(e.consume(C),T):G(C)}function T(C){return C===62?(e.consume(C),R):C===45&&a===2?(e.consume(C),T):G(C)}function R(C){return C===null||Fe(C)?(e.exit("htmlFlowData"),V(C)):(e.consume(C),R)}function V(C){return e.exit("htmlFlow"),t(C)}}function O5(e,t,i){const s=this;return a;function a(c){return Fe(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 z5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Lo,t,i)}}const P5={name:"htmlText",tokenize:I5};function I5(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),O):pn(T)?(e.consume(T),de):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,y):pn(T)?(e.consume(T),z):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):Fe(T)?(c=x,B(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 y(T){const R="CDATA[";return T===R.charCodeAt(o++)?(e.consume(T),o===R.length?N:y):i(T)}function N(T){return T===null?i(T):T===93?(e.consume(T),j):Fe(T)?(c=N,B(T)):(e.consume(T),N)}function j(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 z(T){return T===null||T===62?A(T):Fe(T)?(c=z,B(T)):(e.consume(T),z)}function O(T){return T===null?i(T):T===63?(e.consume(T),W):Fe(T)?(c=O,B(T)):(e.consume(T),O)}function W(T){return T===62?A(T):O(T)}function q(T){return pn(T)?(e.consume(T),D):i(T)}function D(T){return T===45||sn(T)?(e.consume(T),D):te(T)}function te(T){return Fe(T)?(c=te,B(T)):_t(T)?(e.consume(T),te):A(T)}function de(T){return T===45||sn(T)?(e.consume(T),de):T===47||T===62||Gt(T)?_e(T):i(T)}function _e(T){return T===47?(e.consume(T),A):T===58||T===95||pn(T)?(e.consume(T),P):Fe(T)?(c=_e,B(T)):_t(T)?(e.consume(T),_e):A(T)}function P(T){return T===45||T===46||T===58||T===95||sn(T)?(e.consume(T),P):ae(T)}function ae(T){return T===61?(e.consume(T),G):Fe(T)?(c=ae,B(T)):_t(T)?(e.consume(T),ae):_e(T)}function G(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,Y):Fe(T)?(c=G,B(T)):_t(T)?(e.consume(T),G):(e.consume(T),Q)}function Y(T){return T===a?(e.consume(T),a=void 0,I):T===null?i(T):Fe(T)?(c=Y,B(T)):(e.consume(T),Y)}function Q(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||Gt(T)?_e(T):(e.consume(T),Q)}function I(T){return T===47||T===62||Gt(T)?_e(T):i(T)}function A(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function B(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),U}function U(T){return _t(T)?Nt(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 nm={name:"labelEnd",resolveAll:F5,resolveTo:q5,tokenize:W5},H5={tokenize:G5},U5={tokenize:Y5},$5={tokenize:K5};function F5(e){let t=-1;const i=[];for(;++t=3&&(f===null||Fe(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),_t(f)?Nt(e,h,"whitespace")(f):h(f))}}const Nn={continuation:{tokenize:rT},exit:aT,name:"list",tokenize:nT},tT={partial:!0,tokenize:lT},iT={partial:!0,tokenize:sT};function nT(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const y=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Cp(v)){if(s.containerState.type||(s.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(_u,i,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 Cp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),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(Lo,s.interrupt?i:_,e.attempt(tT,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return _t(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 rT(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Lo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Nt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!_t(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(iT,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,Nt(e,e.attempt(Nn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function sT(e,t,i){const s=this;return Nt(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 aT(e){e.exit(this.containerState.type)}function lT(e,t,i){const s=this;return Nt(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!_t(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const Sv={name:"setextUnderline",resolveTo:oT,tokenize:cT};function oT(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 cT(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"),_t(f)?Nt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Fe(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const uT={tokenize:hT};function hT(e){const t=this,i=e.attempt(Lo,s,e.attempt(this.parser.constructs.flowInitial,a,Nt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(g5,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 dT={resolveAll:F0()},fT=$0("string"),pT=$0("text");function $0(e){return{resolveAll:F0(e==="text"?mT: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 TT(e,t){let i=-1;const s=[];let a;for(;++i0){const Ot=Be.tokenStack[Be.tokenStack.length-1];(Ot[1]||Cv).call(Be,void 0,Ot[0])}for(xe.position={start:Ts(ne.length>0?ne[0][1].start:{line:1,column:1,offset:0}),end:Ts(ne.length>0?ne[ne.length-2][1].end:{line:1,column:1,offset:0})},Ge=-1;++Ge0&&(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 $T(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function FT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function qT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=hl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function WT(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 GT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function G0(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 YT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return G0(e,t);const a={src:hl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function KT(e,t){const i={src:hl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function VT(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 XT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return G0(e,t);const a={href:hl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function ZT(e,t){const i={href:hl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function QT(e,t,i){const s=e.all(t),a=i?JT(i):Y0(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 ej(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=Zp(t.children[1]),p=k0(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 sj(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(Nv(t.slice(a),a>0,!1)),o.join("")}function Nv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===kv||o===Ev;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===kv||o===Ev;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function oj(e,t){const i={type:"text",value:lj(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function cj(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const uj={blockquote:IT,break:HT,code:UT,delete:$T,emphasis:FT,footnoteReference:qT,heading:WT,html:GT,imageReference:YT,image:KT,inlineCode:VT,linkReference:XT,link:ZT,listItem:QT,list:ej,paragraph:tj,root:ij,strong:nj,table:rj,tableCell:aj,tableRow:sj,text:oj,thematicBreak:cj,toml:eu,yaml:eu,definition:eu,footnoteDefinition:eu};function eu(){}const K0=-1,Hu=0,So=1,Au=2,rm=3,sm=4,am=5,lm=6,V0=7,X0=8,Tv=typeof self=="object"?self:globalThis,hj=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Hu:case K0:return i(c,a);case So:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Au:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case rm:return i(new Date(c),a);case sm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case am:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case lm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case V0:{const{name:h,message:p}=c;return i(new Tv[h](p),a)}case X0:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Tv[o](c),a)};return s},jv=e=>hj(new Map,e)(0),Ja="",{toString:dj}={},{keys:fj}=Object,fo=e=>{const t=typeof e;if(t!=="object"||!e)return[Hu,t];const i=dj.call(e).slice(8,-1);switch(i){case"Array":return[So,Ja];case"Object":return[Au,Ja];case"Date":return[rm,Ja];case"RegExp":return[sm,Ja];case"Map":return[am,Ja];case"Set":return[lm,Ja];case"DataView":return[So,i]}return i.includes("Array")?[So,i]:i.includes("Error")?[V0,i]:[Au,i]},tu=([e,t])=>e===Hu&&(t==="function"||t==="symbol"),pj=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=fo(c);switch(h){case Hu:{let _=c;switch(p){case"bigint":h=X0,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([K0],c)}return a([h,_],c)}case So:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Au:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of fj(c))(e||!tu(fo(c[b])))&&_.push([o(b),o(c[b])]);return x}case rm:return a([h,c.toISOString()],c);case sm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case am:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(tu(fo(b))||tu(fo(v))))&&_.push([o(b),o(v)]);return x}case lm:{const _=[],x=a([h,_],c);for(const b of c)(e||!tu(fo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Av=(e,{json:t,lossy:i}={})=>{const s=[];return pj(!(t||i),!!t,new Map,s)(e),s},No=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?jv(Av(e,t)):structuredClone(e):(e,t)=>jv(Av(e,t));function mj(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 gj(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function xj(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||mj,s=e.options.footnoteBackLabel||gj,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&y.push({type:"text",value:" "});let z=typeof i=="string"?i:i(p,v);typeof z=="string"&&(z={type:"text",value:z}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(z)?z:[z]})}const j=_[_.length-1];if(j&&j.type==="element"&&j.tagName==="p"){const z=j.children[j.children.length-1];z&&z.type==="text"?z.value+=" ":j.children.push({type:"text",value:" "}),j.children.push(...y)}else _.push(...y);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:{...No(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` +`}]}}const Uu=(function(e){if(e==null)return yj;if(typeof e=="function")return $u(e);if(typeof e=="object")return Array.isArray(e)?_j(e):bj(e);if(typeof e=="string")return vj(e);throw new Error("Expected function, string, or object as test")});function _j(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=Z0,y,N,j;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=kj(i(p,_)),v[0]===Ep))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==Cj)for(N=(s?E.children.length:-1)+c,j=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` +`}),i}function Rv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Mv(e,t){const i=Nj(e,t),s=i.one(e,void 0),a=xj(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function Mj(e,t){return e&&"run"in e?async function(i,s){const a=Mv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Mv(i,{file:s,...e||t})}}function Dv(e){if(e)throw e}var xf,Bv;function Dj(){if(Bv)return xf;Bv=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 xf=function p(){var f,_,x,b,v,y,N=arguments[0],j=1,E=arguments.length,z=!1;for(typeof N=="boolean"&&(z=N,N=arguments[1]||{},j=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});jc.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 Cr={basename:zj,dirname:Pj,extname:Ij,join:Hj,sep:"/"};function zj(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Oo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function Pj(e){if(Oo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Ij(e){Oo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function Hj(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function $j(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Oo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Fj={cwd:qj};function qj(){return"/"}function jp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Wj(e){if(typeof e=="string")e=new URL(e);else if(!jp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Gj(e)}function Gj(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...y]=_;const N=s[b][1];Tp(N)&&Tp(v)&&(v=_f(!0,N,v)),s[b]=[f,v,...y]}}}}const Xj=new cm().freeze();function Sf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Cf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ov(e){if(!Tp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function zv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function iu(e){return Zj(e)?e:new J0(e)}function Zj(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Qj(e){return typeof e=="string"||Jj(e)}function Jj(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const eA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Pv=[],Iv={allowDangerousHtml:!0},tA=/^(https?|ircs?|mailto|xmpp)$/i,iA=[{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 eS(e){const t=nA(e),i=rA(e);return sA(t.runSync(t.parse(i),i),e)}function nA(e){const t=e.rehypePlugins||Pv,i=e.remarkPlugins||Pv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Iv}:Iv;return Xj().use(PT).use(i).use(Mj,s).use(t)}function rA(e){const t=e.children||"",i=new J0;return typeof t=="string"&&(i.value=t),i}function sA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||aA;for(const _ of iA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+eA+_.id,void 0);return om(e,f),yN(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 pf)if(Object.hasOwn(pf,v)&&Object.hasOwn(_.properties,v)){const y=_.properties[v],N=pf[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(y||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function aA(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||tA.test(e.slice(0,t))?e:""}function lA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function tS(e,t,i){const a=Uu((i||{}).ignore||[]),o=oA(t);let c=-1;for(;++c0?{type:"text",value:D}:void 0),D===!1?b.lastIndex=W+1:(y!==W&&z.push({type:"text",value:f.value.slice(y,W)}),Array.isArray(D)?z.push(...D):D&&z.push(D),y=W+O[0].length,E=!0),!b.global)break;O=b.exec(f.value)}return E?(y?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Hv(e,"(");let o=Hv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function nS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||oa(i)||Pu(i))&&(!t||i!==47)}rS.peek=DA;function kA(){this.buffer()}function EA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function NA(){this.buffer()}function TA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function jA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=gr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function AA(e){this.exit(e)}function RA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=gr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function MA(e){this.exit(e)}function DA(){return"["}function rS(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 BA(){return{enter:{gfmFootnoteCallString:kA,gfmFootnoteCall:EA,gfmFootnoteDefinitionLabelString:NA,gfmFootnoteDefinition:TA},exit:{gfmFootnoteCallString:jA,gfmFootnoteCall:AA,gfmFootnoteDefinitionLabelString:RA,gfmFootnoteDefinition:MA}}}function LA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:rS},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?sS:OA))),f(),p}}function OA(e,t,i){return t===0?e:sS(e,t,i)}function sS(e,t,i){return(i?"":" ")+e}const zA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];aS.peek=$A;function PA(){return{canContainEols:["delete"],enter:{strikethrough:HA},exit:{strikethrough:UA}}}function IA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:zA}],handlers:{delete:aS}}}function HA(e){this.enter({type:"delete",children:[]},e)}function UA(e){this.exit(e)}function aS(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 $A(){return"~"}function FA(e){return e.length}function qA(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||FA,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=O)}N.push(z)}c[_]=N,h[_]=j}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=z),v[x]=z),b[x]=O}c.splice(1,0,b),h.splice(1,0,v),_=-1;const y=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),YA);return a(),c}function YA(e,t,i){return">"+(i?"":" ")+e}function KA(e,t){return $v(e,t.inConstruct,!0)&&!$v(e,t.notInConstruct,!1)}function $v(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function XA(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 ZA(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 QA(e,t,i,s){const a=ZA(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(XA(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,JA);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(VA(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 JA(e,t,i){return(i?"":" ")+e}function um(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function eR(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let 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 tR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function To(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ru(e,t,i){const s=al(e),a=al(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}lS.peek=iR;function lS(e,t,i,s){const a=tR(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),_=Ru(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=To(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function iR(e,t,i){return i.options.emphasis||"*"}function nR(e,t){let i=!1;return om(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ep}),!!((!e.depth||e.depth<3)&&tm(e)&&(t.options.setext||i))}function rR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(nR(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=To(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}oS.peek=sR;function oS(e){return e.value||""}function sR(){return"<"}cS.peek=aR;function cS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let 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 aR(){return"!"}uS.peek=lR;function uS(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 lR(){return"!"}hS.peek=oR;function hS(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))}fS.peek=cR;function fS(e,t,i,s){const a=um(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(dS(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 cR(e,t,i){return dS(e,i)?"<":"["}pS.peek=uR;function pS(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 uR(){return"["}function hm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function hR(e){const t=hm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function dR(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 mS(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 fR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?dR(i):hm(i);const h=e.ordered?c==="."?")":".":hR(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),mS(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 gR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const xR=Uu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function _R(e,t,i,s){return(e.children.some(function(c){return xR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function bR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}gS.peek=vR;function gS(e,t,i,s){const a=bR(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),_=Ru(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=To(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Ru(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+To(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function vR(e,t,i){return i.options.strong||"*"}function yR(e,t,i,s){return i.safe(e.value,s)}function SR(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 wR(e,t,i){const s=(mS(i)+(i.options.ruleSpaces?" ":"")).repeat(SR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const xS={blockquote:GA,break:Fv,code:QA,definition:eR,emphasis:lS,hardBreak:Fv,heading:rR,html:oS,image:cS,imageReference:uS,inlineCode:hS,link:fS,linkReference:pS,list:fR,listItem:mR,paragraph:gR,root:_R,strong:gS,text:yR,thematicBreak:wR};function CR(){return{enter:{table:kR,tableData:qv,tableHeader:qv,tableRow:NR},exit:{codeText:TR,table:ER,tableData:Tf,tableHeader:Tf,tableRow:Tf}}}function kR(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 ER(e){this.exit(e),this.data.inTable=void 0}function NR(e){this.enter({type:"tableRow",children:[]},e)}function Tf(e){this.exit(e)}function qv(e){this.enter({type:"tableCell",children:[]},e)}function TR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,jR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function jR(e,t){return t==="|"?t:e}function AR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,y,N,j){return f(_(v,N,j),v.align)}function h(v,y,N,j){const E=x(v,N,j),z=f([E]);return z.slice(0,z.indexOf(` +`))}function p(v,y,N,j){const E=N.enter("tableCell"),z=N.enter("phrasing"),O=N.containerPhrasing(v,{...j,before:o,after:o});return z(),E(),O}function f(v,y){return qA(v,{align:y,alignDelimiters:s,padding:i,stringLength:a})}function _(v,y,N){const j=v.children;let E=-1;const z=[],O=y.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const KR={tokenize:i3,partial:!0};function VR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:JR,continuation:{tokenize:e3},exit:t3}},text:{91:{name:"gfmFootnoteCall",tokenize:QR},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:XR,resolveTo:ZR}}}}function XR(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=gr(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 ZR(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 QR(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||Gt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(gr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Gt(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 JR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(y)}function _(y){if(c>999||y===93&&!h||y===null||y===91||Gt(y))return i(y);if(y===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=gr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Gt(y)||(h=!0),c++,e.consume(y),y===92?x:_}function x(y){return y===91||y===92||y===93?(e.consume(y),c++,_):_(y)}function b(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),a.includes(o)||a.push(o),Nt(e,v,"gfmFootnoteDefinitionWhitespace")):i(y)}function v(y){return t(y)}}function e3(e,t,i){return e.check(Lo,t,e.attempt(KR,t,i))}function t3(e){e.exit("gfmFootnoteDefinition")}function i3(e,t,i){const s=this;return Nt(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 n3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(y):(c.consume(y),x++,v);if(x<2&&!i)return p(y);const j=c.exit("strikethroughSequenceTemporary"),E=al(y);return j._open=!E||E===2&&!!N,j._close=!N||N===2&&!!E,h(y)}}}class r3{constructor(){this.map=[]}add(t,i,s){s3(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 s3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Q=s.events[ae][1].type;if(Q==="lineEnding"||Q==="linePrefix")ae--;else break}const G=ae>-1?s.events[ae][1].type:null,Y=G==="tableHead"||G==="tableRow"?D:p;return Y===D&&s.parser.lazy[s.now().line]?i(P):Y(P)}function p(P){return e.enter("tableHead"),e.enter("tableRow"),f(P)}function f(P){return P===124||(c=!0,o+=1),_(P)}function _(P){return P===null?i(P):Fe(P)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),v):i(P):_t(P)?Nt(e,_,"whitespace")(P):(o+=1,c&&(c=!1,a+=1),P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(P)))}function x(P){return P===null||P===124||Gt(P)?(e.exit("data"),_(P)):(e.consume(P),P===92?b:x)}function b(P){return P===92||P===124?(e.consume(P),x):x(P)}function v(P){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(P):(e.enter("tableDelimiterRow"),c=!1,_t(P)?Nt(e,y,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):y(P))}function y(P){return P===45||P===58?j(P):P===124?(c=!0,e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),N):q(P)}function N(P){return _t(P)?Nt(e,j,"whitespace")(P):j(P)}function j(P){return P===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),E):P===45?(o+=1,E(P)):P===null||Fe(P)?W(P):q(P)}function E(P){return P===45?(e.enter("tableDelimiterFiller"),z(P)):q(P)}function z(P){return P===45?(e.consume(P),z):P===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),O):(e.exit("tableDelimiterFiller"),O(P))}function O(P){return _t(P)?Nt(e,W,"whitespace")(P):W(P)}function W(P){return P===124?y(P):P===null||Fe(P)?!c||a!==o?q(P):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(P)):q(P)}function q(P){return i(P)}function D(P){return e.enter("tableRow"),te(P)}function te(P){return P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),te):P===null||Fe(P)?(e.exit("tableRow"),t(P)):_t(P)?Nt(e,te,"whitespace")(P):(e.enter("data"),de(P))}function de(P){return P===null||P===124||Gt(P)?(e.exit("data"),te(P)):(e.consume(P),P===92?_e:de)}function _e(P){return P===92||P===124?(e.consume(P),de):de(P)}}function c3(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 r3;for(;++ii[2]+1){const y=i[2]+1,N=i[3]-i[2]-1;e.add(y,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},el(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Gv(e,t,i,s,a){const o=[],c=el(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function el(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const u3={name:"tasklistCheck",tokenize:d3};function h3(){return{text:{91:u3}}}function d3(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 Gt(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 Fe(p)?t(p):_t(p)?e.check({tokenize:f3},t,i)(p):i(p)}}function f3(e,t,i){return Nt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function p3(e){return D0([IR(),VR(),n3(e),l3(),h3()])}const m3={};function ES(e){const t=this,i=e||m3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(p3(i)),o.push(LR()),c.push(OR(i))}const ta=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ll={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ta,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ta],h2:[["className","sr-only"]],img:[...ta,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ta,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ta],table:[...ta],ul:[...ta,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},As={}.hasOwnProperty;function g3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ll,...t}:ll,stack:[]},a=NS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function NS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return x3(e,i);case"doctype":return _3(e,i);case"element":return b3(e,i);case"root":return v3(e,i);case"text":return y3(e,i)}}}function x3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return zo(o,t),o}}function _3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return zo(i,t),i}}function b3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=TS(e,t.children),a=S3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&As.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function AS(e){return function(t){return g3(t,e)}}const nl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],Xr=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function RS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const k3=Object.fromEntries(nl.map(e=>[RS(e),e])),E3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function bu(e){if(!e)return null;const t=RS(e.trim());return t?k3[t]??E3[t]??null:null}function MS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function DS(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(MS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function Rp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=DS(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 Vv(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function ru(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),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 j=a.hasSpeaker?N*c:0,E=a.hasSpeaker?j*o:0,z=Math.max(1,_-E),O=a.fontWeight??400,W=Vv((te,de)=>e(te,de,O),t,f,N),q=W.length*N*o,D=W.every(te=>e(te,N,O)<=f+.5);return{lines:W,ok:q<=z&&D}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:j,ok:E}=v(N);return{lines:j,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:j,ok:E}=v(N);if(E)return{lines:j,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:Vv(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function N3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const BS=["speech","narration","sfx"],T3=2;function Er(e,t,i){return Math.min(i,Math.max(t,e))}function rl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Er(e,t,i):void 0}function fm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=rl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=rl(t.lineHeightFactor,.9,2),c=rl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Fu(e){if(!e||typeof e!="object")return;const t=e,i=rl(t.paddingX,0,.25),s=rl(t.paddingY,0,.25),a=rl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function su(e,t,i,s){const{minFontSize:a,maxFontSize:o}=N3(t),c=fm(e.textStyle),h=Fu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function j3(e,t,i){const s=Fu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function LS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Xv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Er(e,h,p):t+i/2,half:c}}function OS(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??LS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:z,half:O}=Xv(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:z-O,y:E},base2:{x:z+O,y:E}}}const y=_>=0?e+i:e,{center:N,half:j}=Xv(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:y,y:N-j},base2:{x:y,y:N+j}}}function A3(e){return e.type!=="speech"||!e.tailAnchor?!1:OS(0,0,1,1,e.tailAnchor)!==null}function R3(e,t,i,s,a,o){const c=o??LS(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 M3(e,t,i,s,a,o){const c=R3(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 D3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let Zv=0;function Qv(e,t=.1,i=.1){return Zv++,{id:`overlay-${Date.now()}-${Zv}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function B3(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const au=.05;function Ui(e){return typeof e=="number"&&Number.isFinite(e)}function L3(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?au:Er(o?1-t-au:(1-t)/2,0,1),_=c?au:Er(h?1-i-au:(1-i)/2,0,1);return{x:f,y:_}}let O3=0;function z3(e){if(!e||typeof e!="object")return null;const t=e,i=BS.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"?L3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Er(c,0,1),h=Er(h,0,1),a=Er(a,.02,1),o=Er(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++O3}`,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 _=fm(t.textStyle),x=Fu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function P3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&BS.includes(t.type)&&Ui(t.x)&&Ui(t.y)&&Ui(t.width)&&Ui(t.height)&&typeof t.text=="string"}function I3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=z3(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),P3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function ZD(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=fm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Fu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const Jv=new Set(["speech","narration"]),H3=.12;function ey(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 U3(e,t=H3){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 ar(e){return e.kind==="text"}function $3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||ar(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function zS(e,t=T3){return!e.finalImagePath||!(e.overlays??[]).some(A3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ty,height:Math.round(ty*s/i)}}function lu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?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(Rp,{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(Rp,{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(lu,{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(lu,{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(lu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(lu,{cut:e}),s&&(()=>{const f=$3(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 W3({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 y=await b.json();f(y.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 iy=/!\[[^\]]*\]\([^)]*\)/g,G3=//g,PS=200;function Y3(e){const t=(e.match(iy)||[]).length,i=e.length,s=e.replace(G3," ").replace(iy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,PS)}}function K3(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 V3=[/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 X3(e){for(const t of V3){const i=e.match(t);if(i)return i[0]}return null}function pm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=X3(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 HS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(Z3(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=IS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const jf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function Q3(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 US(e){const t=c=>{var h;return((h=jf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...jf.map(c=>c.key),"other"],a=c=>{var h;return((h=jf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:Q3(h)})}return o}const J3=220,Af=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function mm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Af.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Af.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Af.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function eM(e){return/\.(webp|jpe?g)$/i.test(e)}function Mp(e){var c;let t=0,i=0,s=0,a=0,o=0;for(const h of e)ar(h)||(t++,h.cleanImagePath&&eM(h.cleanImagePath)&&(i++,(((c=h.overlays)==null?void 0:c.length)??0)>0&&s++)),h.finalImagePath&&h.exportedAt&&a++,h.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const tM={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function ou(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function iM(e){const{cuts:t,published:i=!1}=e,s=Mp(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.needClean,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(z=>!_[z]),v=z=>s.needClean>0?ou(z,s.needClean):"no image cuts",y={plan:ou(s.total,s.total),clean:v(s.withClean),letter:v(s.withText),export:ou(s.exported,s.total),upload:ou(s.uploaded,s.total),publish:null},N=x.map((z,O)=>({key:z,label:tM[z],status:b===-1||OPS,a=sM({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] ${lM[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(eS,{remarkPlugins:[iS,ES],rehypePlugins:[[AS,aM]],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 cM="modulepreload",uM=function(e){return"/"+e},ny={},ry=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=uM(f),f in ny)return;ny[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":cM,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,y)=>{b.addEventListener("load",v),b.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${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)})},gm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],hM="system-ui, sans-serif",dM=gm.find(e=>e.family==="Noto Sans"),fM=gm.find(e=>e.category==="display");function pM(e){return gm.find(i=>i.category==="body"&&i.languages.includes(e))||dM}function mM(){return fM}function gM(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function sy(e){return`"${e.family}", ${hM}`}function xM(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function vu(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function _M(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==vu(e.current)}function $S(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}const bM={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},vM="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",yM="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 SM(e){var a;const t=bM[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(yM),s.push(vM),s.join(` +`).trim()}function wM(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function ay(e,t){const i=wM(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",SM(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` +`)}function CM(e,t){const i=`${t}.cuts.json`,s=$S(e),a=s.length>0?s.map(o=>o.type==="speech"?`- speech — ${o.speaker||"Speaker"}: "${o.text}"`:o.type==="narration"?`- narration: ${o.text}`:`- sfx: ${o.text}`).join(` +`):"- (no dialogue/narration/SFX recorded for this cut — add a caption only if the scene needs one)";return[`Draft the speech bubbles and captions for cut ${e.id} of ${t}.`,"","Script to letter:",a,"","How to draft it:",`- Edit cut ${e.id}'s "overlays" array in ${i}: add one overlay per line above — "type":"speech" for dialogue (also set "speaker"), "narration" for captions, "sfx" for sound effects, with the line's text.`,"- Position each overlay with x, y, width, height as 0–1 fractions of the panel, roughly where it belongs over the art, and keep bubbles clear of faces.","- These are DRAFT positions only: do NOT export or upload. The writer reviews and adjusts them in the OWS lettering editor, then exports the final image there."].join(` +`)}function En(e,t){return e*t}function ly(e,t){return t===0?0:e/t}function oy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=gM(e),document.head.appendChild(i)}const yu={speech:"Speech",narration:"Narration",sfx:"SFX"},kM={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Rf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:yu[e.type]}const cy=.05,EM=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function cu(e,t,i){return Math.min(i,Math.max(t,e))}function NM({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1}){var Mt,ct,We,Bt,pt,Mi;const _=pM(c),x=mM(),b=sy(_),v=sy(x);w.useEffect(()=>{oy(_),oy(x)},[_,x]),w.useEffect(()=>{let H=!1;return ae(!1),(async()=>{try{const{ensureFontsReady:ke}=await ry(async()=>{const{ensureFontsReady:Pe}=await import("./export-cut-BdY0Az65.js");return{ensureFontsReady:Pe}},[]);await ke([_.family,x.family])}catch{}H||ae(!0)})(),()=>{H=!0}},[_.family,x.family]);const y=DS(e,t.cleanImagePath,h),N=w.useMemo(()=>I3(t.overlays),[t.overlays]),j=N.invalid.length,[E,z]=w.useState(!1),O=j===0&&N.changed&&N.overlays.length>0,[W,q]=w.useState(()=>N.overlays),[D,te]=w.useState(()=>vu(N.overlays)),de=w.useRef(null),_e=w.useCallback(H=>(ke,Pe,je=400)=>{var Xe;!de.current&&typeof document<"u"&&(de.current=document.createElement("canvas"));const Ie=(Xe=de.current)==null?void 0:Xe.getContext("2d");return Ie?(Ie.font=`${je} ${Pe}px ${H}`,Ie.measureText(ke).width):ke.length*Pe*.5},[]),[P,ae]=w.useState(!1),[G,Y]=w.useState(null),[Q,I]=w.useState(!1),[A,B]=w.useState(!1),[U,ge]=w.useState(null),[T,R]=w.useState(null),[V,C]=w.useState(!1),[K,re]=w.useState({x:0,y:0,width:0,height:0}),ue=w.useRef(null),$=w.useRef(null),le=w.useRef(null),be=w.useCallback(()=>{const H=ue.current;if(!H)return;const ke=H.clientWidth,Pe=H.clientHeight;let je,Ie;if(t.kind==="text"){const Tt=F3(t.aspectRatio)??{width:800,height:600};je=Tt.width,Ie=Tt.height}else{const Tt=$.current;if(!Tt||!Tt.naturalWidth)return;je=Tt.naturalWidth,Ie=Tt.naturalHeight}if(!ke||!Pe)return;const Xe=Math.min(ke/je,Pe/Ie),mt=je*Xe,Qe=Ie*Xe;re({x:(ke-mt)/2,y:(Pe-Qe)/2,width:mt,height:Qe})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=ue.current;if(!H)return;const ke=new ResizeObserver(()=>be());return ke.observe(H),()=>ke.disconnect()},[be]);const Te=w.useCallback(H=>{const ke=B3(H.type,H.x,H.y),Pe=ke.width,je=Math.max(.08,1-H.y);if(!H.text||!P||K.width<=0)return ke;const Ie=H.type==="sfx"?v:b,Xe=En(Pe,K.width);let mt=H.type==="sfx"?.08:.12;for(let Qe=0;Qe<24;Qe++){const Tt=Math.min(mt,je),qt=En(Tt,K.height);if(!ru(_e(Ie),H.text,Xe,qt,su({...H},K.height||300,Xe,qt)).overflow||Tt>=je)return{width:Pe,height:Tt};mt+=.03}return{width:Pe,height:Math.min(mt,je)}},[P,K,_e,b,v]),Le=w.useCallback(H=>{const ke=Qv(H,.1+Math.random()*.3,.1+Math.random()*.3),Pe={...ke,...Te(ke)};q(je=>[...je,Pe]),Y(Pe.id)},[Te]),ze=w.useCallback(H=>{const Pe={...Qv(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},je={...Pe,...Te(Pe)};q(Ie=>[...Ie,je]),Y(je.id)},[Te]),ye=w.useCallback((H,ke)=>{q(Pe=>Pe.map(je=>je.id===H?{...je,...ke}:je))},[]),rt=w.useCallback(H=>{var mt;const ke=K.height||300,Pe=K.width>0?En(H.width,K.width):200,je=K.height>0?En(H.height,K.height):100,Ie=H.type==="sfx"?v:b,Xe=ru(_e(Ie),H.text,Pe,je,su({...H,textStyle:void 0},ke,Pe,je));ye(H.id,{textStyle:{mode:"manual",fontScale:Xe.fontSize/Math.max(1,ke),fontWeight:((mt=H.textStyle)==null?void 0:mt.fontWeight)??400,lineHeightFactor:Xe.fontSize>0?Xe.lineHeight/Xe.fontSize:1.2,speakerScale:Xe.fontSize>0&&Xe.speakerFontSize>0?Xe.speakerFontSize/Xe.fontSize:.8}})},[K,v,b,_e,ye]),bt=w.useCallback(H=>{q(ke=>ke.filter(Pe=>Pe.id!==H)),Y(null),I(!1)},[]),wt=w.useCallback(()=>{Y(null),I(!1)},[]),vt=w.useCallback((H,ke)=>{H.stopPropagation(),Y(ke),I(!1)},[]),Ve=w.useCallback((H,ke,Pe)=>{H.stopPropagation(),H.preventDefault();const je=W.find(Ie=>Ie.id===ke);je&&(Y(ke),le.current={id:ke,mode:Pe,startX:H.clientX,startY:H.clientY,origX:je.x,origY:je.y,origW:je.width,origH:je.height})},[W]);w.useEffect(()=>{const H=Pe=>{const je=le.current;if(!je||K.width===0)return;const Ie=ly(Pe.clientX-je.startX,K.width),Xe=ly(Pe.clientY-je.startY,K.height);if(je.mode==="move"){const mt=cu(je.origX+Ie,0,1-je.origW),Qe=cu(je.origY+Xe,0,1-je.origH);ye(je.id,{x:mt,y:Qe})}else{const mt=cu(je.origW+Ie,cy,1-je.origX),Qe=cu(je.origH+Xe,cy,1-je.origY);ye(je.id,{width:mt,height:Qe})}},ke=()=>{le.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",ke),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",ke)}},[K,ye]);const Me=w.useCallback(async()=>{R(null);try{await s(W),f&&a()}catch(H){R(H instanceof Error?H.message:"Failed to save overlays")}},[W,s,a,f]),Je=w.useCallback(()=>{var H;(H=navigator.clipboard)==null||H.writeText(CM(t,i)),C(!0),setTimeout(()=>C(!1),2e3)},[t,i]),It=w.useCallback(async()=>{if(j>0&&!E){const H=j;ge(`${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}B(!0),ge(null);try{await s(W);const{exportCut:H,ensureFontsReady:ke}=await ry(async()=>{const{exportCut:oe,ensureFontsReady:Ee}=await import("./export-cut-BdY0Az65.js");return{exportCut:oe,ensureFontsReady:Ee}},[]),Pe=W.some(oe=>oe.type==="sfx"),je=[_.family,...Pe?[x.family]:[]],{ready:Ie,missing:Xe}=await ke(je);if(!Ie){ge(`Fonts not loaded: ${Xe.join(", ")}. Check your connection and retry.`),B(!1);return}if(t.cleanImagePath&&!y.url){ge(y.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),B(!1);return}const mt=y.url,Qe=await H(mt,W,b,v,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),Tt=new FormData,qt=Qe.type==="image/webp"?"webp":"jpg";Tt.append("file",Qe,`cut-${t.id}.${qt}`);const li=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:Tt});if(li.ok)te(vu(W)),o==null||o();else{const oe=await li.json();ge(oe.error||"Export failed")}}catch(H){ge(H instanceof Error?H.message:"Export failed")}finally{B(!1)}},[t,y,W,e,i,_,x,b,v,h,s,o,j,E]),Ae=W.find(H=>H.id===G),ii=w.useMemo(()=>U3(W),[W]),Ct=w.useRef(t.id);w.useEffect(()=>{Ct.current!==t.id&&(Ct.current=t.id,te(vu(N.overlays)))},[t.id,N.overlays]);const pi=_M({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:D,current:W}),ne=w.useMemo(()=>xM({...t,overlays:W},{staleExport:pi}),[t,W,pi]),xe=w.useMemo(()=>$S(t),[t]),Be=w.useMemo(()=>{const H={};for(const ke of W){const Pe=D3(ke);let je=!1;if(P&&K.width>0&&ke.text){const Ie=ke.type==="sfx"?v:b,Xe=En(ke.width,K.width),mt=En(ke.height,K.height);je=ru(_e(Ie),ke.text,Xe,mt,su(ke,K.height||300,Xe,mt)).overflow}(Pe||je)&&(H[ke.id]={outOfBounds:Pe,overflow:je})}return H},[W,P,K,_e,b,v]),$e=Object.keys(Be).length,Ge=t.kind==="text",Ot=!t.cleanImagePath;return!Ge&&Ot&&W.length===0&&!t.narration&&!((Mt=t.dialogue)!=null&&Mt.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:[W.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[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"})]}),U&&d.jsx("span",{className:"text-[10px] text-error",children:U}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),d.jsx("button",{onClick:It,disabled:A,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:A?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Me()},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&&!E?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:()=>z(!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","."]}):O?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,ii.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,": ",ii.length," bubble ",ii.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",ii.map(H=>`#${H.indexA+1} ${Rf(W[H.indexA])} ↔ #${H.indexB+1} ${Rf(W[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",ne.hasCleanImage],["script-text","Script text",ne.hasScriptText],["bubbles",`Bubbles placed${ne.bubblesPlaced?` (${ne.bubblesPlaced})`:""}`,ne.bubblesPlaced>0],["exported","Final exported",ne.exported],["uploaded","Uploaded",ne.uploaded]].map(([H,ke,Pe])=>d.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Pe?"true":"false",className:`flex items-center gap-1 ${Pe?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Pe?"✓":"○"}),ke]},H))}),pi&&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."}),$e>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:[$e," bubble",$e===1?"":"s"," may not export cleanly:"," ",Object.entries(Be).map(([H,ke])=>{const Pe=W.findIndex(Ie=>Ie.id===H),je=[ke.outOfBounds?"outside image":null,ke.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Pe+1} ${Rf(W[Pe])} (${je})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:ue,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:wt,"data-testid":"editor-surface",children:[t.cleanImagePath&&y.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&&!y.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:$,src:y.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:be}):Ge?K.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:K.x,top:K.y,width:K.width,height:K.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&&K.width===0){const ke=H.getBoundingClientRect();ke.width>0&&re({x:0,y:0,width:ke.width,height:ke.height})}},children:"Narration cut"}),K.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:W.map(H=>{if(H.type!=="speech")return null;const ke=K.x+En(H.x,K.width),Pe=K.y+En(H.y,K.height),je=En(H.width,K.width),Ie=En(H.height,K.height),Xe=j3(H,je,Ie),mt=H.tailAnchor?OS(ke,Pe,je,Ie,H.tailAnchor,Xe):null,Qe=Math.max(1.5,K.height*.004),Tt=H.id===G;return d.jsx("path",{"data-testid":`balloon-${H.id}`,d:M3(ke,Pe,je,Ie,mt,Xe),className:`fill-white/95 ${Tt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:Tt?Qe+.5:Qe,strokeLinejoin:"round"},H.id)})}),K.width>0&&W.map(H=>{const ke=K.x+En(H.x,K.width),Pe=K.y+En(H.y,K.height),je=En(H.width,K.width),Ie=En(H.height,K.height),Xe=H.id===G,mt=H.type==="speech",Qe=H.type==="narration",Tt=!!Be[H.id];return d.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":Tt?"true":"false",onClick:qt=>vt(qt,H.id),onMouseDown:qt=>Ve(qt,H.id,"move"),className:`absolute rounded cursor-move select-none ${mt?"":`border-2 ${kM[H.type]}`} ${Qe?"bg-[#f4efe6]/85 rounded-md":""} ${Xe&&!mt?"ring-2 ring-accent":""} ${Tt?"ring-2 ring-amber-500":""}`,style:{left:ke,top:Pe,width:je,height:Ie},children:[(()=>{var Ee,Ue;const qt=H.type==="sfx"?v:b;if(!H.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:qt},children:yu[H.type]});const li=H.type!=="sfx"&&!!H.speaker;if(!P)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:qt,fontSize:Math.max(9,Math.min(Ie*.05,16)),fontWeight:((Ee=H.textStyle)==null?void 0:Ee.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:li?`${H.speaker}: ${H.text}`:H.text});const oe=ru(_e(qt),H.text,je,Ie,su(H,K.height,je,Ie));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:qt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[li&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:oe.speakerFontSize,lineHeight:1.2},children:H.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:oe.fontSize,lineHeight:`${oe.lineHeight}px`,fontWeight:((Ue=H.textStyle)==null?void 0:Ue.fontWeight)??400},children:oe.lines.map((Ye,ee)=>d.jsx("span",{className:"block",children:Ye},ee))})]})})(),Xe&&d.jsx("div",{onMouseDown:qt=>{qt.stopPropagation(),Ve(qt,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:[d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1.5","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft assist"}),d.jsxs("p",{className:"text-[11px] text-muted",children:["Copy a prompt scoped to ",p??`cut ${t.id}`,". Review and edit any drafted bubbles here before saving."]}),d.jsx("button",{type:"button",onClick:Je,className:"rounded border border-accent/40 px-2 py-1 text-[11px] font-medium text-accent hover:bg-accent/10","data-testid":"copy-ai-lettering-current",children:V?"Copied!":"Copy AI draft prompt"})]}),xe.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:xe.map(H=>d.jsxs("button",{onClick:()=>ze(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:["+ ",yu[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))})]}),Ae?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:yu[Ae.type]}),Ae.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:Ae.speaker||"",onChange:H=>ye(Ae.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:Ae.text,onChange:H=>ye(Ae.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:()=>ye(Ae.id,Te(Ae)),"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"}),((ct=Ae.textStyle)==null?void 0:ct.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>ye(Ae.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:()=>rt(Ae),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"})]}),((We=Ae.textStyle)==null?void 0:We.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:((Ae.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>ye(Ae.id,{textStyle:{...Ae.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(Ae.textStyle.fontWeight??400),onChange:H=>ye(Ae.id,{textStyle:{...Ae.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:(Ae.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>ye(Ae.id,{textStyle:{...Ae.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"})]}),Ae.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:(Ae.textStyle.speakerScale??.8).toFixed(2),onChange:H=>ye(Ae.id,{textStyle:{...Ae.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."})]}),Ae.type==="speech"&&(()=>{const H=Ae.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:EM.map(ke=>d.jsx("button",{type:"button",onClick:()=>ye(Ae.id,{tailAnchor:ke.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-${ke.key}`,children:ke.label},ke.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:ke=>ye(Ae.id,{tailAnchor:{...H,x:parseFloat(ke.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:ke=>ye(Ae.id,{tailAnchor:{...H,y:parseFloat(ke.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"})]})]})]})})(),Ae.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:((((Bt=Ae.bubbleStyle)==null?void 0:Bt.paddingX)??.06)*100).toFixed(0),onChange:H=>ye(Ae.id,{bubbleStyle:{...Ae.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:((((pt=Ae.bubbleStyle)==null?void 0:pt.paddingY)??.08)*100).toFixed(0),onChange:H=>ye(Ae.id,{bubbleStyle:{...Ae.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:((((Mi=Ae.bubbleStyle)==null?void 0:Mi.cornerRadius)??.4)*100).toFixed(0),onChange:H=>ye(Ae.id,{bubbleStyle:{...Ae.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: ",Ae.type==="sfx"?x.family:_.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Ae.x.toFixed(3),", y: ",Ae.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Ae.width.toFixed(3),", h: ",Ae.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{Q?bt(Ae.id):I(!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:Q?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const FS=12e3,TM=5,jM=6e4,AM=6e4,RM=5;function MM(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function DM(e,t=FS){return Math.min(t*2**e,jM)}const qS=e=>new Promise(t=>setTimeout(t,e));async function BM(e,t={}){var c;const i=t.sleep??qS,s=t.maxRetries??TM,a=t.baseDelayMs??FS;let o=0;for(;;){const h=await e();if(h.ok||!MM(h.status,h.errorMessage)||o>=s)return h;const p=DM(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function LM(e={}){const t=e.limit??RM,i=e.windowMs??AM,s=e.sleep??qS,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 Dp=1024*1024;function uy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function OM(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await uy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=Dp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await uy(e,"image/jpeg",s);if(a.size<=Dp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const zM=["image/webp","image/jpeg"];function WS(e){return zM.includes(e.type)&&e.size<=Dp}async function PM(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function qu(e){if(WS(e))return e;const t=await PM(e);return OM(t)}function IM(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 HM(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(IM):[]}async function UM(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 $M(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 FM(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function qM(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 WM({image:e,authFetch:t}){const i=$M(`/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 GM({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 z=await HM(e);E||o(z)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),y=Date.now(),N=async E=>{h(null),f(E.token);try{const z=await UM(e,E);await i(z)}catch(z){h(z instanceof Error?z.message:"Could not import the generated image")}finally{f(null)}},j=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"})]}),j&&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."}),j&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),j&&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(WM,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[qM(E.mtimeMs,y)," · ",FM(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 YM={done:"✓",current:"▸",todo:"○"};function KM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var N;if(!e||e.steps.length===0)return null;const p=US(t),f=((N=e.steps.find(j=>j.key==="upload"))==null?void 0:N.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}],y=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode";return d.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/50 space-y-2 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]})]}),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:YM[j.status]}),d.jsx("span",{children:j.label}),j.detail&&d.jsxs("span",{className:"text-muted",children:["· ",j.detail]})]},j.key))}),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-3 py-1 text-xs border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:y}),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((E,z)=>d.jsx("li",{children:E},z))})]},j.key))})]})}function VM(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 GS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":ar(e)?"text":"missing"}const hy={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},XM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function ZM(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"}:ar(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 QM(e){var t;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?{label:"Draft saved",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} placed`,tone:"amber"}:ar(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 JM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:f,syncing:_,staleMessages:x,onRepairStale:b,repairing:v,conversionPng:y,onConvert:N,converting:j,rowRef:E}){var ue;const z=w.useRef(null),[O,W]=w.useState(!1),[q,D]=w.useState(null),[te,de]=w.useState(!1),[_e,P]=w.useState(!1),[ae,G]=w.useState(!1),[Y,Q]=w.useState(!1),I=GS(e),A=x.length>0,B=!!y,U=w.useCallback(async()=>{y&&(Q(!0),await N(e.id,y),Q(!1),c())},[y,N,e.id,c]),ge=w.useCallback(async $=>{W(!0),D(null);try{let le=$;if(!WS($))try{le=await qu($)}catch(ze){return D(ze instanceof Error?ze.message:"Could not import image"),!1}const be=le.type==="image/jpeg"?"jpg":"webp",Te=new FormData;Te.append("file",new File([le],`clean.${be}`,{type:le.type}));const Le=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Te});if(!Le.ok){const ze=await Le.json();return D(ze.error||"Upload failed"),!1}return c(),!0}catch{return D("Upload failed"),!1}finally{W(!1)}},[o,t,i,e.id,c]),T=ZM(e,B,A),R=e.cleanImagePath??y??null,V=((ue=e.overlays)==null?void 0:ue.length)??0,C=!ar(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!A&&!B,K=T.key==="convert"?{label:Y?"Converting…":"Convert image",onClick:U,testid:`card-convert-${e.id}`}:T.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:T.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:T.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null,re=QM(e);return d.jsxs("div",{ref:E,"data-cut-row":e.id,className:`border rounded ${s?"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 ${XM[T.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 ${hy[T.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:T.label})]}),R?d.jsx(Rp,{storyName:t,assetPath:R,authFetch:o,alt:`Cut ${e.id} artwork`,className:"w-full max-h-[32rem] object-contain rounded border border-border bg-white"}):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:ar(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] ${hy[re.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:re.label}),d.jsxs("span",{className:"text-muted",children:[" · ",re.detail]})]}),d.jsx("button",{onClick:a,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[C?d.jsx("button",{onClick:h,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:V>0?"Review lettering":"Open focused editor"}):K?d.jsx("button",{onClick:K.onClick,disabled:T.key==="convert"&&(Y||j),"data-testid":K.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:K.label}):null,d.jsx("button",{onClick:a,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:s?"Hide details":"Open details"})]})]}),s&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[B&&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:U,disabled:Y||j,"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:Y?"Converting…":"Convert image"})]}),A&&!B&&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:[x.map(($,le)=>d.jsx("p",{className:"text-[11px] text-error",children:$},le)),d.jsx("button",{onClick:b,disabled:v,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:v?"Repairing…":"Clear stale path"})]}),!ar(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(ay(e,i)),de(!0),setTimeout(()=>de(!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:te?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:z,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:$=>{var be;const le=(be=$.target.files)==null?void 0:be[0];le&&ge(le),$.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var $;return($=z.current)==null?void 0:$.click()},disabled:O,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:O?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>G($=>!$),disabled:O,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:ae?"Hide Codex images":"Import from Codex"})]}),ae&&d.jsx(GM,{authFetch:o,cutId:e.id,onImport:async $=>{await ge($)&&G(!1)},onClose:()=>G(!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."}),I==="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(ay(e,i)),P(!0),setTimeout(()=>P(!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:_e?"Copied!":"Copy Codex task"})]}),I==="missing"&&p&&d.jsx("button",{onClick:f,disabled:_,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:_?"Syncing...":"Found local clean image — sync to cut plan"}),q&&d.jsx("p",{className:"text-xs text-error mt-1",children:q})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||ar(e))&&d.jsx("button",{onClick:h,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&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(($,le)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[$.speaker,":"]})," ",$.text]},le))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function dy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h}){var Tt,qt,li;const[p,f]=w.useState(null),_=w.useRef(o);_.current=o;const x=w.useRef(h);x.current=h;const[b,v]=w.useState(!0),[y,N]=w.useState(null),[j,E]=w.useState(null),[z,O]=w.useState(null),[W,q]=w.useState(!1),[D,te]=w.useState([]),[de,_e]=w.useState(!1),[P,ae]=w.useState(""),[G,Y]=w.useState({markdownReady:!1,published:!1}),[Q,I]=w.useState(!1),[A,B]=w.useState(!1),[U,ge]=w.useState(!1),[T,R]=w.useState(null),[V,C]=w.useState(null),[K,re]=w.useState(new Set),[ue,$]=w.useState(new Map),[le,be]=w.useState(!1),[Te,Le]=w.useState(null),[ze,ye]=w.useState(!1),[rt,bt]=w.useState(null),wt=w.useRef(new Map),vt=w.useRef(null),Ve=t.replace(/\.md$/,"");w.useEffect(()=>{var oe;c&&vt.current!==c.seq&&(vt.current=c.seq,c.openEditor?O(c.cutId):(E(c.cutId),bt(c.cutId)),(oe=x.current)==null||oe.call(x))},[c]),w.useEffect(()=>{var Ee;if(rt==null)return;const oe=wt.current.get(rt);oe&&((Ee=oe.scrollIntoView)==null||Ee.call(oe,{behavior:"smooth",block:"center"}),bt(null))},[rt,p]);const Me=w.useCallback(async()=>{var oe;try{const Ee=await i(`/api/stories/${e}/cuts/${Ve}`);if(Ee.status===404){f(null);return}if(!Ee.ok){const Ye=await Ee.json();N(Ye.error||"Failed to load cuts");return}const Ue=await Ee.json();f(Ue),N(null);try{const Ye=await i(`/api/stories/${e}/${t}`);if(Ye.ok){const ee=await Ye.json(),me=typeof(ee==null?void 0:ee.content)=="string"?ee.content:"",Ce=Array.isArray(Ue==null?void 0:Ue.cuts)?Ue.cuts:[],ut=me.length>0&&IS(me,Ce).ready,ot=(ee==null?void 0:ee.status)==="published"||(ee==null?void 0:ee.status)==="published-not-indexed";Y({markdownReady:ut,published:ot})}else Y({markdownReady:!1,published:!1})}catch{Y({markdownReady:!1,published:!1})}(oe=_.current)==null||oe.call(_)}catch{N("Failed to load cuts")}finally{v(!1)}},[i,e,Ve,t]),Je=w.useCallback(async()=>{be(!1);try{const oe=await i(`/api/stories/${e}/cuts/${Ve}/detect-clean-images`);if(!oe.ok)return;const Ee=await oe.json();re(new Set(Array.isArray(Ee.detected)?Ee.detected:[]));const Ue=new Map,Ye=Ee.stale;if(Array.isArray(Ye))for(const ee of Ye){if(typeof(ee==null?void 0:ee.cutId)!="number"||typeof(ee==null?void 0:ee.message)!="string")continue;const me=Ue.get(ee.cutId)??[];me.push(ee.message),Ue.set(ee.cutId,me)}$(Ue),be(!0)}catch{}},[i,e,Ve]),It=w.useCallback(async()=>{Le(null);try{const oe=await i(`/api/stories/${e}/cuts/${Ve}/asset-diagnostics`);if(!oe.ok)return;const Ee=await oe.json();Le(Array.isArray(Ee.diagnostics)?Ee.diagnostics:null)}catch{}},[i,e,Ve]),Ae=w.useCallback(async()=>{ye(!0);try{await Promise.all([Me(),Je(),It()])}finally{ye(!1)}},[Me,Je,It]),ii=w.useCallback(async()=>{I(!0),C(null),te([]);try{const oe=await i(`/api/stories/${e}/cuts/${Ve}/sync-clean-images`,{method:"POST"}),Ee=await oe.json().catch(()=>({}));if(!oe.ok)C(Ee.error||"Sync failed");else{const Ue=Array.isArray(Ee.synced)?Ee.synced.length:0,Ye=Array.isArray(Ee.cleared)?Ee.cleared.length:0,ee=Array.isArray(Ee.rejected)?Ee.rejected:[];ee.length>0&&te(ee.map(Ce=>`Cut ${Ce.cutId}: ${Ce.reason}`));const me=[];Ue>0&&me.push(`Synced ${Ue}`),Ye>0&&me.push(`Cleared ${Ye} stale path${Ye===1?"":"s"}`),C(me.length>0?me.join(", "):"No new clean images"),await Me(),await Je(),await It()}}catch{C("Sync failed")}I(!1)},[i,e,Ve,Me,Je,It]),Ct=w.useCallback(async(oe,Ee)=>{try{const Ue=await i(MS(e,Ee));if(!Ue.ok)return!1;const Ye=await Ue.blob(),ee=await qu(new File([Ye],"clean.png",{type:Ye.type||"image/png"})),me=ee.type==="image/jpeg"?"jpg":"webp",Ce=new FormData;return Ce.append("file",new File([ee],`clean.${me}`,{type:ee.type})),(await i(`/api/stories/${e}/cuts/${Ve}/upload-clean/${oe}`,{method:"POST",body:Ce})).ok}catch{return!1}},[i,e,Ve]),pi=w.useCallback(async oe=>{ge(!0),R(null);let Ee=0;const Ue=[];for(const Ye of oe)await Ct(Ye.cutId,Ye.pngPath)?Ee++:Ue.push(Ye.cutId);await Ae(),ge(!1),R(Ue.length===0?`Converted ${Ee} image${Ee===1?"":"s"} to WebP`:`Converted ${Ee}; ${Ue.length} failed (Cut ${Ue.join(", ")}) — try Convert image on each`)},[Ct,Ae]),ne=w.useCallback(async()=>{var ee;if(!p)return;_e(!0),ae(""),te([]);const oe=p.cuts.filter(me=>me.finalImagePath&&!me.uploadedCid),Ee=[],Ue=LM({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:me})=>ae(`Upload limit reached — waiting ${Math.round(me/1e3)}s before continuing…`)});for(let me=0;me{const Lt=await i("/api/publish/upload-plot-image",{method:"POST",body:st});if(Lt.ok){const{cid:Fi,url:Fn}=await Lt.json();return{ok:!0,status:Lt.status,cid:Fi,url:Fn}}const oi=await Lt.json().catch(()=>({}));return{ok:!1,status:Lt.status,errorMessage:oi.error}},{...a,onWaiting:({attempt:Lt,maxRetries:oi,waitMs:Fi})=>ae(`Cut ${Ce.id} rate-limited — waiting ${Math.round(Fi/1e3)}s before retry ${Lt}/${oi}...`)});if(!it.ok){Ee.push(`Cut ${Ce.id}: upload failed — ${it.errorMessage||"unknown"}`);continue}const{cid:kt,url:ht}=it;(await i(`/api/stories/${e}/cuts/${Ve}/set-uploaded/${Ce.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:kt,url:ht})})).ok||Ee.push(`Cut ${Ce.id}: failed to record upload`)}catch(ut){Ee.push(`Cut ${Ce.id}: ${ut instanceof Error?ut.message:"failed"}`)}}if(Ee.length>0){te(Ee),_e(!1),ae(""),Me();return}ae("Preparing episode for publishing…");const Ye=await i(`/api/stories/${e}/cuts/${Ve}/generate-markdown`,{method:"POST"});if(Ye.ok){const me=await Ye.json();((ee=me.warnings)==null?void 0:ee.length)>0&&te(me.warnings)}_e(!1),ae(""),Me()},[p,i,e,Ve,a,Me]),xe=w.useCallback(async()=>{B(!0),C(null);try{const oe=await i(`/api/stories/${e}/cuts/${Ve}/repair-asset-paths`,{method:"POST"}),Ee=await oe.json().catch(()=>({}));if(!oe.ok)C(Ee.error||"Repair failed");else{const Ue=Array.isArray(Ee.cleared)?Ee.cleared.length:0;C(Ue>0?`Cleared ${Ue} stale path${Ue===1?"":"s"}`:"No stale paths to clear"),await Me(),await Je()}}catch{C("Repair failed")}B(!1)},[i,e,Ve,Me,Je]),[Be,$e]=w.useState(!1),Ge=w.useCallback(async(oe,Ee=!0)=>{if(p){$e(!0);try{const Ue=p.cuts.reduce((ut,ot)=>Math.max(ut,ot.id),0)+1,Ye={id:Ue,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=[...p.cuts];ee.splice(Math.max(0,Math.min(oe,ee.length)),0,Ye);const me={...p,cuts:ee},Ce=await i(`/api/stories/${e}/cuts/${Ve}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(me)});if(Ce.ok)Ee?O(Ue):E(Ue),await Me();else{const ut=await Ce.json().catch(()=>({}));C(ut.error||"Could not add text panel")}}catch{C("Could not add text panel")}$e(!1)}},[p,i,e,Ve,Me]),Ot=w.useCallback(()=>Ge((p==null?void 0:p.cuts.length)??0,!0),[Ge,p]);if(w.useEffect(()=>{Me(),Je(),It()},[Me,Je,It]),b)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(y)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:y}),d.jsxs("p",{className:"text-xs text-muted",children:[Ve,".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:Me,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!p||p.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 Mt=z!==null?p.cuts.find(oe=>oe.id===z):null;if(Mt)return d.jsx(NM,{storyName:e,cut:Mt,plotFile:Ve,language:s,authFetch:i,targetLabel:ar(Mt)?`Between-scene card ${Mt.id}`:`Cut ${String(Mt.id).padStart(2,"0")}`,returnOnSave:!0,onSave:async oe=>{const Ee={...p,cuts:p.cuts.map(Ye=>Ye.id===z?{...Ye,overlays:oe}:Ye)},Ue=await i(`/api/stories/${e}/cuts/${Ve}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ee)});if(!Ue.ok){const Ye=await Ue.json().catch(()=>({}));throw new Error(Ye.error||"Failed to save overlays")}},onExported:()=>Me(),onClose:()=>{O(null),Me()}});const ct=p.cuts.reduce((oe,Ee)=>{const Ue=GS(Ee);return oe[Ue]++,oe},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),We=p.cuts.filter(oe=>!ar(oe)).length,Bt=p.cuts.filter(oe=>zS(oe)).map(oe=>oe.id),pt=iM({cuts:p.cuts,published:G.published}),Mi=((Tt=pt.steps.find(oe=>oe.key==="upload"))==null?void 0:Tt.status)==="done",H=p.cuts.some(oe=>oe.finalImagePath&&!oe.uploadedCid)||Mi&&!G.markdownReady,ke=(Te??[]).filter(oe=>oe.state==="needs-conversion"&&oe.convertiblePng).map(oe=>({cutId:oe.cutId,pngPath:oe.convertiblePng})),Pe=new Map(ke.map(oe=>[oe.cutId,oe.pngPath])),je=(Te??[]).filter(oe=>oe.state==="needs-conversion"&&oe.issue).map(oe=>oe.issue),Ie=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((qt=Ve.match(/\d+/))==null?void 0:qt[0])??"0",10)+1}`,Xe=typeof p.title=="string"?p.title:null,mt=p.cuts.filter(oe=>!ar(oe)),Qe={cuts:p.cuts.length,artwork:mt.filter(oe=>oe.cleanImagePath||Pe.has(oe.id)).length,converted:mt.filter(oe=>oe.cleanImagePath&&/\.(webp|jpe?g)$/i.test(oe.cleanImagePath)).length,lettered:p.cuts.filter(oe=>{var Ee;return(((Ee=oe.overlays)==null?void 0:Ee.length)??0)>0||!!oe.finalImagePath}).length,uploaded:p.cuts.filter(oe=>oe.uploadedCid||oe.uploadedUrl).length};return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsxs("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-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:Ie}),Xe&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Xe]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Qe.cuts," cuts · ",Qe.artwork," artwork found · ",Qe.converted," converted · ",Qe.lettered," lettered · ",Qe.uploaded," uploaded"]})]}),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:[p.cuts.length," cuts"]}),ct.missing>0&&d.jsxs("span",{className:"text-muted",children:[ct.missing," missing"]}),ct.clean>0&&d.jsxs("span",{className:"text-green-700",children:[ct.clean," clean"]}),ct.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[ct.lettered," lettered"]}),ct.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[ct.uploaded," uploaded"]}),ct.text>0&&d.jsxs("span",{className:"text-accent",children:[ct.text," text ",ct.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{q(!0),te([]);try{const oe=await i(`/api/stories/${e}/cuts/${Ve}/generate-markdown`,{method:"POST"});if(oe.ok){const Ee=await oe.json();te(Ee.warnings||[])}}catch{}q(!1)},disabled:W,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:W?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ot,disabled:Be,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:Be?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Ae,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:ii,disabled:Q,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:Q?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:ne,disabled:de||!(p!=null&&p.cuts.some(oe=>oe.finalImagePath&&!oe.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:P||"Upload & Prepare for Publish"})]})]}),d.jsxs("div",{className:"px-3 py-2 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",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."]})]}),Bt.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:[Bt.length===1?"Cut":"Cuts"," ",Bt.join(", ")," ",Bt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export ",Bt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),le&&We>0&&ct.missing===0&&ue.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 ",We," clean image",We===1?"":"s"," present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),V&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:V}),ke.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:[ke.length," PNG image",ke.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>pi(ke),disabled:U,"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:U?"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."}),T&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:T}),je.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:je.map((oe,Ee)=>d.jsx("li",{children:oe},Ee))})]})]}),Te&&Te.length>0&&(()=>{const oe=VM(Te),Ee=Te.filter(Ue=>Ue.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: ",oe.uploaded," uploaded · ",oe.finalReady," final · ",oe.cleanReady," clean · ",oe.planned," planned",oe.needsConversion>0?` · ${oe.needsConversion} needs conversion`:"",oe.missing>0?` · ${oe.missing} missing`:""]}),Ee.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:Ee.map(Ue=>d.jsx("li",{children:Ue.issue},Ue.cutId))})]})})(),d.jsx(KM,{checklist:pt,issues:D,onFinish:ne,finishing:de,progressText:P,canFinish:H,markdownReady:G.markdownReady,published:G.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[p.cuts.map((oe,Ee)=>{var Ue;return d.jsxs(w.Fragment,{children:[d.jsx(fy,{index:Ee,beforeLabel:Ee===0?"Episode opening":`After cut ${(Ue=p.cuts[Ee-1])==null?void 0:Ue.id}`,afterLabel:`Before cut ${oe.id}`,disabled:Be,onAdd:()=>Ge(Ee)}),d.jsx(JM,{cut:oe,storyName:e,plotFile:Ve,expanded:j===oe.id,onToggle:()=>E(j===oe.id?null:oe.id),authFetch:i,onUpdated:()=>{Me(),Je(),It()},onOpenEditor:()=>O(oe.id),detectedLocalClean:K.has(oe.id),onSyncClean:ii,syncing:Q,staleMessages:ue.get(oe.id)??[],onRepairStale:xe,repairing:A,conversionPng:Pe.get(oe.id)??null,onConvert:Ct,converting:U,rowRef:Ye=>{Ye?wt.current.set(oe.id,Ye):wt.current.delete(oe.id)}})]},oe.id)}),d.jsx(fy,{index:p.cuts.length,beforeLabel:`After cut ${(li=p.cuts[p.cuts.length-1])==null?void 0:li.id}`,afterLabel:"Episode ending",disabled:Be,onAdd:()=>Ge(p.cuts.length)})]})]})}function fy({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 xm({coach:e,onAction:t,className:i="",showEmptyState:s=!1}){const[a,o]=w.useState(null),c=a!==null&&a===(e==null?void 0:e.prompt);return e===void 0?null:e?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 eD({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(xm,{coach:c,onAction:a,showEmptyState:o})}const tD=1024*1024,iD=["image/webp","image/jpeg"],nD="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function rD(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 py(e){return e.size>tD?"Image exceeds 1MB limit":iD.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function sD(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Bp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function aD(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function jo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function lD(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Lp(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function _m(e){var s;const t=Bp(e.fileContent);if(t)return!Lp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Lp(i)}function bm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Bp(i);if(t==="genesis.md"){const p=a?Bp(a):null;return(h??p??aD(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=lD(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function oD(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function cD(e){return oD(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function my(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function uD(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Mf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Df(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function hD(e){return!!e&&e.ready===!1}function dD(e){const t=Df(e.requiredBalance)??Df(e.creationFee),i=Df(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const fD={...ll,attributes:{...ll.attributes,img:["src","alt","title"]}},pD="https://ipfs.filebase.io/ipfs/";function mD(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 gD(e){const t=mD(e),i=[];for(const a of t)a.url.startsWith(pD)||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 xD({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}){const[y,N]=w.useState(null),[j,E]=w.useState(!1),[z,O]=w.useState("preview"),[W,q]=w.useState("publish"),[D,te]=w.useState("text"),[de,_e]=w.useState(null),P=w.useCallback((ie,Se)=>{O("edit"),_e(Ne=>({cutId:ie,openEditor:Se,seq:((Ne==null?void 0:Ne.seq)??0)+1}))},[]),[ae,G]=w.useState(""),[Y,Q]=w.useState(!1),[I,A]=w.useState(!1),[B,U]=w.useState(!1),[ge,T]=w.useState(null),[R,V]=w.useState(""),[C,K]=w.useState(""),[re,ue]=w.useState(!1),[$,le]=w.useState(null),[be,Te]=w.useState(0),[Le,ze]=w.useState(0),[ye,rt]=w.useState(null),[bt,wt]=w.useState(null),[vt,Ve]=w.useState(null),[Me,Je]=w.useState(0),It=w.useRef(null),Ae=w.useRef(!1),[ii,Ct]=w.useState(!1),[pi,ne]=w.useState(nl[0]),[xe,Be]=w.useState(Xr[0]),[$e,Ge]=w.useState(!1),[Ot,Mt]=w.useState(null),[ct,We]=w.useState(null),[Bt,pt]=w.useState(!1),[Mi,H]=w.useState(!1),[ke,Pe]=w.useState(!1),[je,Ie]=w.useState(null),[Xe,mt]=w.useState(!1),Qe=w.useRef(null),Tt=w.useRef(null),[qt,li]=w.useState(!1),[oe,Ee]=w.useState(null),[Ue,Ye]=w.useState(null),[ee,me]=w.useState("unknown"),Ce=w.useRef(!1),[ut,ot]=w.useState(!1),[tt,st]=w.useState(!1),[it,kt]=w.useState(null),[ht,Kt]=w.useState([]),[Lt,oi]=w.useState(null),Fi=w.useRef(null),Fn=w.useRef(null),qi=w.useCallback(async()=>{if(!e||!t){N(null);return}const ie=`${e}/${t}`,Se=Fn.current!==ie;Se&&(Fn.current=ie);try{const Ne=await i(`/api/stories/${e}/${t}`);if(Ne.ok){const Ze=await Ne.json();N(Ze),(Se||!Ae.current)&&(G(Ze.content??""),Se&&(A(!1),Ae.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{E(!0),qi().finally(()=>E(!1))},[qi]),w.useEffect(()=>{if(!e||!t||z==="edit"&&I)return;const ie=setInterval(qi,3e3);return()=>clearInterval(ie)},[e,t,qi,z,I]);const[ni,jn]=w.useState(null),qn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!qn||!e){jn(null);return}let ie=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Se=>Se.ok?Se.json():null).then(Se=>{ie||jn(Se?Mp(Se.cuts||[]):null)}).catch(()=>{ie||jn(null)}),()=>{ie=!0}},[qn,e,i]);const ri=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!ri||!e||!t){le(null),Te(0),ze(0),rt(null);return}let ie=!1;const Se=t.replace(/\.md$/,"");return rt(null),(async()=>{try{const[Ne,Ze]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Se}`)]);if(ie)return;if(!Ze.ok){le("error"),Te(0),ze(0),rt(null);return}const jt=await Ze.json(),_i=jt.cuts||[],Rn=Ne.ok?(await Ne.json()).content??"":"",un=HS(Rn,_i);ie||(le(un.stage),Te(un.awaitingCount),ze(un.totalCuts),rt(Mp(_i)),Ve(typeof jt.title=="string"?jt.title:null))}catch{ie||(le("error"),Te(0),ze(0),rt(null))}})(),()=>{ie=!0}},[ri,e,t,i,y==null?void 0:y.content,y==null?void 0:y.status,Me]),w.useEffect(()=>{if(!e){wt(null);return}let ie=!1;return i(`/api/stories/${e}/structure.md`).then(Se=>Se.ok?Se.json():null).then(Se=>{ie||wt((Se==null?void 0:Se.content)??null)}).catch(()=>{}),()=>{ie=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ie=bu(p);let Se=ie??"";if(!ie&&bt){const Ze=bt.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Ze&&(Se=bu(Ze[1].replace(/\*+/g,"").trim())??"")}V(Se);let Ne=h&&Xr.find(Ze=>Ze.toLowerCase()===h.toLowerCase())||"";if(!Ne&&bt){const Ze=bt.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Ze&&(Ne=Xr.find(jt=>jt.toLowerCase()===Ze[1].replace(/\*+/g,"").trim().toLowerCase())||"")}K(Ne),ue(f??!1)},[e,p,h,f,bt]);const Vt=w.useCallback(ie=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ie)}).catch(()=>{})},[e,i]),Wn=w.useCallback(async()=>{if(!(!e||!t)){Q(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:ae})})).ok&&(A(!1),Ae.current=!1,N(Se=>Se&&{...Se,content:ae}))}catch{}Q(!1)}},[e,t,i,ae]),ln=w.useCallback(async()=>{if(!e||!t)return;const ie=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ie}/generate-markdown`,{method:"POST"})).ok&&(await qi(),Je(Ne=>Ne+1))}catch{}},[e,t,i,qi]),An=w.useCallback((ie,Se)=>{if(ie==="view-progress"){x==null||x();return}if(Se&&Se!==t){b==null||b(Se);return}switch(ie){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":O("edit"),te("cuts");break;case"generate-markdown":ln();break;case"publish":O("preview");break}},[t,x,b,ln]),ts=w.useCallback(ie=>{var Ze;const Se=(Ze=ie.target.files)==null?void 0:Ze[0];if(!Se)return;Ce.current=!0,Ee(null),Ye(null);const Ne=py(Se);if(Ne){Mt(null),We(jt=>(jt&&URL.revokeObjectURL(jt),null)),Qe.current&&(Qe.current.value=""),Ie(Ne),me("invalid");return}Mt(Se),We(jt=>(jt&&URL.revokeObjectURL(jt),URL.createObjectURL(Se))),Ie(null),me("selected")},[]),Jt=w.useCallback(async ie=>{var Ne;const Se=(Ne=ie.target.files)==null?void 0:Ne[0];if(Tt.current&&(Tt.current.value=""),!(!Se||!e)){Ce.current=!0,Ee(null),li(!0),Ie(null);try{let Ze;try{Ze=await qu(Se)}catch(hr){Mt(null),We(Ls=>(Ls&&URL.revokeObjectURL(Ls),null)),Ie(hr instanceof Error?hr.message:"Could not import image");return}const jt=Ze.type==="image/jpeg"?"jpg":"webp",_i=new File([Ze],`cover.${jt}`,{type:Ze.type}),Rn=new FormData;Rn.append("file",_i);const un=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Rn});if(!un.ok){const hr=await un.json().catch(()=>({}));Ie(hr.error||"Cover import failed");return}Mt(_i),We(hr=>(hr&&URL.revokeObjectURL(hr),URL.createObjectURL(_i))),Ye(null),me("selected"),Ie(null)}catch{Ie("Cover import failed")}finally{li(!1)}}},[e,i]),xn=w.useCallback(async ie=>{if(ie.size>1024*1024){kt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ie.type)){kt("Only WebP and JPEG images are accepted");return}st(!0),kt(null);try{const Ne=new FormData;Ne.append("file",ie);const Ze=await i("/api/publish/upload-plot-image",{method:"POST",body:Ne});if(!Ze.ok){const _i=await Ze.json();throw new Error(_i.error||"Upload failed")}const jt=await Ze.json();Kt(_i=>[..._i,{cid:jt.cid,url:jt.url}])}catch(Ne){kt(Ne instanceof Error?Ne.message:"Upload failed")}finally{st(!1),Fi.current&&(Fi.current.value="")}},[i]),dl=w.useCallback(ie=>{var Ne;const Se=(Ne=ie.target.files)==null?void 0:Ne[0];Se&&xn(Se)},[xn]),Ar=w.useCallback(async()=>{if(y!=null&&y.storylineId){pt(!0),Ie(null),mt(!1);try{let ie;if(Ot){const Ne=new FormData;Ne.append("file",Ot);const Ze=await i("/api/publish/upload-cover",{method:"POST",body:Ne});if(!Ze.ok){const _i=await Ze.json();throw new Error(_i.error||"Cover upload failed")}ie=(await Ze.json()).cid}const Se=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:y.storylineId,...ie!==void 0&&{coverCid:ie},genre:pi,language:xe,isNsfw:$e})});if(!Se.ok){const Ne=await Se.json();throw new Error(Ne.error||"Update failed")}mt(!0),Mt(null),ie!==void 0&&(Pe(!0),We(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),me("unknown"),Qe.current&&(Qe.current.value="")),setTimeout(()=>mt(!1),3e3)}catch(ie){Ie(ie instanceof Error?ie.message:"Update failed")}finally{pt(!1)}}},[y==null?void 0:y.storylineId,Ot,pi,xe,$e,i]);w.useEffect(()=>{Ct(!1),Mt(null),We(null),Ie(null),mt(!1),H(!1),ot(!1),Kt([]),kt(null),Ee(null),Ye(null),me("unknown"),Ce.current=!1,te("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!y||y.storylineId||y.status==="published"||y.status==="published-not-indexed"||Ce.current)return;let ie=!1;return(async()=>{try{const Se=await i(`/api/stories/${e}/cover-asset`);if(ie||!Se.ok)return;const Ne=await Se.json();if(ie)return;if(!(Ne!=null&&Ne.found)){me("none");return}if(!Ne.valid){Ye(Ne.error||"Detected cover asset is invalid and was not used"),me("invalid");return}const Ze=await i(`/api/stories/${e}/asset/${Ne.path.replace(/^assets\//,"")}`);if(ie||!Ze.ok)return;const jt=await Ze.blob(),_i=new File([jt],Ne.path.split("/").pop()||"cover.webp",{type:Ne.type});if(py(_i)||ie||Ce.current)return;Mt(_i),We(Rn=>(Rn&&URL.revokeObjectURL(Rn),URL.createObjectURL(_i))),Ee(Ne.path),me("detected")}catch{}})(),()=>{ie=!0}},[e,t,y,y==null?void 0:y.status,y==null?void 0:y.storylineId,i]),w.useEffect(()=>{if(!ii||!(y!=null&&y.storylineId))return;H(!1);const ie="https://plotlink.xyz";let Se=!1;return fetch(`${ie}/api/storyline/${y.storylineId}`).then(Ne=>Ne.ok?Ne.json():null).then(Ne=>{if(!Se){if(!Ne){Ie("Could not load current story metadata");return}if(Ne.genre){const Ze=bu(Ne.genre);Ze&&ne(Ze)}if(Ne.language){const Ze=Xr.find(jt=>jt.toLowerCase()===Ne.language.toLowerCase());Ze&&Be(Ze)}Ne.isNsfw!==void 0&&Ge(!!Ne.isNsfw),Pe(!!(Ne.coverCid||Ne.coverUrl||Ne.cover)),H(!0)}}).catch(()=>{Se||Ie("Could not load current story metadata")}),()=>{Se=!0}},[ii,y==null?void 0:y.storylineId]),w.useEffect(()=>{if(z!=="edit")return;const ie=Se=>{(Se.metaKey||Se.ctrlKey)&&Se.key==="s"&&(Se.preventDefault(),Wn())};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[z,Wn]),w.useEffect(()=>{if((y==null?void 0:y.status)!=="published-not-indexed"||!y.publishedAt)return;const ie=new Date(y.publishedAt).getTime(),Se=300*1e3,Ne=()=>{const jt=Math.max(0,Se-(Date.now()-ie));T(jt)};Ne();const Ze=setInterval(Ne,1e3);return()=>clearInterval(Ze)},[y==null?void 0:y.status,y==null?void 0:y.publishedAt]);const or=ge!==null&&ge<=0,_n=ge!==null&&ge>0?`${Math.floor(ge/6e4)}:${String(Math.floor(ge%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(j&&!y)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const ha=(z==="edit"?ae:(y==null?void 0:y.content)??"").length,Ji=t==="genesis.md",cr=t?/^plot-\d+\.md$/.test(t):!1,en=c==="cartoon"&&cr,on=c==="cartoon"&&Ji,da=on||en,Ei=(y==null?void 0:y.status)==="published"||(y==null?void 0:y.status)==="published-not-indexed",fa=on?ni?ni.total:null:en?$===null?null:Le:null,pa=rM({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Ei,cutCount:fa,cutProgress:on?ni:null}),ma=(on||en)&&!Ei,Gn=ma?bm({fileName:t,fileContent:(y==null?void 0:y.content)??"",storySlug:e??"",structureContent:bt,contentType:"cartoon",episodeTitle:vt}):null,ga=!!Gn&&jo(Gn,t),fl=en&&!Ei&&!_m({fileContent:(y==null?void 0:y.content)??"",episodeTitle:vt}),Yn=on&&!Ei?mm((y==null?void 0:y.content)??""):null,Po=!!Yn&&Yn.blockers.length>0,Io="w-full max-w-[32rem] rounded-xl border px-3 py-3",Ho={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},xa=ie=>{if(!on)return null;const Se=rD({hasSelectedCover:!!Ot,invalid:ee==="invalid",attached:ie});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Se.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${Ho[Se.tone]}`,children:Se.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:nD})]})]})},pl=ga||fl,Wu=()=>{if(!ma||!Gn)return null;const ie=Ji?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":ga?"true":"false","data-blocked":pl?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ie,":"]})," ",d.jsx("span",{className:pl?"text-error font-medium":"text-foreground",children:Gn})]}),ga?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Ji?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):fl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Gn,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},_a=()=>Yn?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":Po?"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."}),Yn.blockers.map((ie,Se)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ie},`b-${Se}`)),Yn.warnings.map((ie,Se)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ie},`w-${Se}`))]}):null,cn=Ji||cr?1e4:null,is=!Ei&&cn!==null&&ha>cn,ml=(y==null?void 0:y.content)??"",ur=Ei?{count:0,warnings:[]}:gD(ml),Rr=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:It,value:ae,onChange:ie=>{G(ie.target.value),A(!0),Ae.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}),d.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs text-muted",children:I?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:Wn,disabled:!I||Y,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:Y?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full flex flex-col",children:[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]}),(y==null?void 0:y.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(y==null?void 0:y.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:y.indexError,children:"Published (not indexed)"}),(y==null?void 0:y.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 ${is?"text-error font-medium":"text-muted"}`,children:[ha.toLocaleString(),cn!==null?`/${cn.toLocaleString()}`:" chars"]}),is&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(ha-cn).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>O("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${z==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>O("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${z==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",I&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),c==="cartoon"&&e&&t&&d.jsx(eD,{storyName:e,fileName:t,authFetch:i,refreshKey:Me,onAction:An,showEmptyState:!0}),z==="preview"?en?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:()=>q("publish"),className:`px-2 py-0.5 text-[11px] rounded ${W==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>q("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${W==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:W==="publish"?d.jsx(oM,{content:(y==null?void 0:y.content)??"",stage:$}):d.jsx(W3,{storyName:e,fileName:t,authFetch:i,onEditCut:P})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:y!=null&&y.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(eS,{remarkPlugins:[iS,ES],rehypePlugins:[[AS,fD]],children:y.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):en?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(dy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Je(ie=>ie+1),focusRequest:de,onFocusHandled:()=>_e(null)})}):on?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:()=>te("text"),className:`px-2 py-0.5 text-[11px] rounded ${D==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>te("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${D==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:D==="cuts"?d.jsx(dy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>Je(ie=>ie+1),focusRequest:de,onFocusHandled:()=>_e(null)}):Rr})]}):Rr,d.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:pa}):(y==null?void 0:y.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"}),!or&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!y.txHash)){U(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:y.txHash,content:y.content,storylineId:y.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:y.txHash,storylineId:y.storylineId,contentCid:"",gasCost:""})}),qi())}catch{}U(!1)}},disabled:B,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:B?"Retrying...":`Retry Index${_n?` (${_n})`:""}`}),cr&&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,R,C,re)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),y.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:or?cr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":cr?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),y.indexError&&d.jsx("p",{className:"text-error text-xs",children:y.indexError})]}):(y==null?void 0:y.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"}),y.storylineId&&d.jsx("a",{href:(()=>{var Ne;const ie=`https://plotlink.xyz/story/${y.storylineId}`;if(!cr)return ie;const Se=y.plotIndex!=null&&y.plotIndex>0?y.plotIndex:parseInt(((Ne=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ne[1])??"1");return`${ie}/${Se}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),y.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${y.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ji&&o&&y.storylineId&&(!y.authorAddress||y.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Ct(ie=>!ie),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ii?"Close Edit":"Edit Story"})]}),ii&&Ji&&y.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"}),xa(ke),d.jsxs("div",{className:"flex items-start gap-3",children:[ct&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:ct,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Mt(null),We(null),Ye(null),me("unknown"),Qe.current&&(Qe.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:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:ts,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:pi,onChange:ie=>ne(ie.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:nl.map(ie=>d.jsx("option",{value:ie,children:ie},ie))}),d.jsx("select",{value:xe,onChange:ie=>Be(ie.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:Xr.map(ie=>d.jsx("option",{value:ie,children:ie},ie))})]}),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:ie=>Ge(ie.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:Ar,disabled:Bt||!Mi,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Bt?"Saving...":Mi?"Save Changes":"Loading..."}),Xe&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),je&&d.jsx("span",{className:"text-error text-xs",children:je})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[en&&ye&&ye.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:ye.total})]}),d.jsxs("span",{children:["Clean: ",d.jsxs("span",{className:"text-foreground font-medium",children:[ye.withClean,"/",ye.needClean]})]}),d.jsxs("span",{children:["Lettered: ",d.jsxs("span",{className:"text-foreground font-medium",children:[ye.withText,"/",ye.needClean]})]}),d.jsxs("span",{children:["Uploaded: ",d.jsxs("span",{className:"text-foreground font-medium",children:[ye.uploaded,"/",ye.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),on&&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"]})]}),(on||en)&&pa&&d.jsxs("div",{className:`${Io} 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:fa===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:on?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:pa})]}),cr&&!en&&z==="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:ut,onChange:ie=>ot(ie.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),ut&&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 ie;return(ie=Fi.current)==null?void 0:ie.click()},onDragOver:ie=>{ie.preventDefault(),ie.stopPropagation()},onDrop:ie=>{var Ne;ie.preventDefault(),ie.stopPropagation();const Se=(Ne=ie.dataTransfer.files)==null?void 0:Ne[0];Se&&xn(Se)},children:[d.jsx("input",{ref:Fi,type:"file",accept:"image/webp,image/jpeg",onChange:dl,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:tt?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),it&&d.jsx("span",{className:"text-error text-xs",children:it}),ht.map((ie,Se)=>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](",ie.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ie.url})`),oi(Se),setTimeout(()=>oi(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Lt===Se?"Copied!":"Copy"})]})]},ie.cid))]})]}),Ji&&c!=="cartoon"&&!(z==="edit"&&D==="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)"})]}),xa(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[ct&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:ct,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Ce.current=!0,Ee(null),Ye(null),me("unknown"),Mt(null),We(ie=>(ie&&URL.revokeObjectURL(ie),null)),Qe.current&&(Qe.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:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:ts,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:Tt,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Jt,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ie;return(ie=Tt.current)==null?void 0:ie.click()},disabled:qt,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:qt?"Importing…":"Import generated image (PNG ok)"}),Ot&&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."}),oe&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",oe," — pick a file to override."]}),Ue&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[Ue," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&ee==="none"&&!Ot&&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."]}),je&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:je})]})]})]}),!da&&Wu(),!da&&_a(),!da&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ji&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:R,"data-testid":"publish-genre-select",onChange:ie=>{V(ie.target.value),ie.target.value&&Vt({genre:ie.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${R?"border-border":"border-amber-500"}`,children:[!R&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),nl.map(ie=>d.jsx("option",{value:ie,children:ie},ie))]}),d.jsxs("select",{value:C,"data-testid":"publish-language-select",onChange:ie=>{K(ie.target.value),ie.target.value&&Vt({language:ie.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${C?"border-border":"border-amber-500"}`,children:[!C&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),Xr.map(ie=>d.jsx("option",{value:ie,children:ie},ie))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(ur.count>0){const Se=`This plot contains ${ur.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. + +Please verify illustrations appear correctly in Preview before continuing. + +Publish now?`;if(!window.confirm(Se))return}const ie=Ji?Ot:null;ie?await(s==null?void 0:s(e,t,R,C,re,ie))&&(Ce.current=!0,Ee(null),Ye(null),me("unknown"),Mt(null),We(Ne=>(Ne&&URL.revokeObjectURL(Ne),null)),Qe.current&&(Qe.current.value="")):s==null||s(e,t,R,C,re)},disabled:!!a||is||pl||Po||Ji&&(!R||!C)||en&&$!=="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"}),Ji&&c==="cartoon"&&(!R||!C)&&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"}),Ji&&c!=="cartoon"&&!R&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ji&&c!=="cartoon"&&R&&!C&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),is&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),en&&$==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),en&&$==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),en&&$==="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” — ",be," of ",Le," still need an uploaded image"]})]}),da&&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 →"}),ur.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:ur.warnings.map((ie,Se)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ie},Se))}),Ji&&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:re,onChange:ie=>{ue(ie.target.checked),Vt({isNsfw:ie.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),re&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function _D(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 YS(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 bD({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:_D(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 KS({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return YS(e)==="story-info"?d.jsx(bD,{progress:e,onOpenStoryInfo:i}):d.jsx(xm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function vD({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(yD(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?d.jsx(KS,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):d.jsx(xm,{coach:null,showEmptyState:!0,onAction:s})}function yD(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function SD({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(jD,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(MD,{progress:o,storyName:e,onOpenFile:i})}function uu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return 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 VS({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(uu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(uu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(uu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(uu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const XS={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Mu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},ZS={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},wD={done:"✓",current:"◓",todo:"○"},CD={done:"text-green-700",current:"text-accent",todo:"text-muted"};function QS({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:`${CD[e.status]} flex-shrink-0`,"aria-hidden":!0,children:wD[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 gy({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 ${Mu[i]}`,"aria-hidden":!0,children:XS[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 ${Mu[i]} flex-shrink-0`,children:ZS[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(QS,{item:h},p))})]})}function kD(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function ED(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(ND(a));return s}function ND(e){return{label:e.label,status:e.status,detail:e.detail}}const TD={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function jD({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=YS(e),_=d.jsx(KS,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,z)=>{E!=="view-progress"&&z&&i(t,z)}}),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",y=e.episodes.find(E=>E.kind==="genesis")??null,N=e.episodes.filter(E=>E.kind==="plot");let j=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(VS,{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(gy,{index:++j,title:"Define Story Info",status:b,items:x}),d.jsx(gy,{index:++j,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),y?d.jsx(Bf,{index:++j,ep:y,isActive:f===y.file,storyName:t,onOpenFile:i}):d.jsx(Bf,{index:++j,ep:TD,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),N.map(E=>d.jsx(Bf,{index:++j,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 Bf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=kD(t,i),p=ED(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 ${Mu[h]}`,"aria-hidden":!0,children:XS[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 ${Mu[h]} flex-shrink-0`,children:ZS[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(QS,{item:x},b))})]})}const AD={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},xy={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},RD={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function MD({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(VS,{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(_y,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(_y,{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 ${xy[o.state]}`,"aria-hidden":!0,children:AD[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 ${xy[o.state]}`,children:RD[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 _y({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 DD=[{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 BD({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:DD.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 LD({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,y]=w.useState(""),[N,j]=w.useState(!1),[E,z]=w.useState("cartoon"),[O,W]=w.useState("unknown"),[q,D]=w.useState(!1),[te,de]=w.useState(!1),[_e,P]=w.useState(null),[ae,G]=w.useState(!1),[Y,Q]=w.useState(null),[I,A]=w.useState(!1),B=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),de(!1),P(null),(async()=>{try{const[K,re]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!K.ok){C||(c(!0),a(!1));return}const ue=await K.json(),$=re.ok?await re.json().catch(()=>null):null;if(C)return;p(ue.title??""),_(ue.description??""),b(bu(ue.genre)??""),y(ue.language&&Xr.find(le=>le.toLowerCase()===ue.language.toLowerCase())||""),j(!!ue.isNsfw),z(ue.contentType==="fiction"?"fiction":"cartoon"),W(($==null?void 0:$.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const U=w.useCallback(async()=>{D(!0),de(!1),P(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const K=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(K.ok)de(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const re=await K.json().catch(()=>({}));P(re.error||"Could not save story info.")}}catch{P("Could not save story info.")}D(!1)},[e,t,h,f,x,v,N,i]),ge=w.useCallback(async C=>{var re;const K=(re=C.target.files)==null?void 0:re[0];if(B.current&&(B.current.value=""),!!K){G(!0),P(null);try{let ue;try{ue=await qu(K)}catch(Le){P(Le instanceof Error?Le.message:"Could not import image");return}const $=ue.type==="image/jpeg"?"jpg":"webp",le=new File([ue],`cover.${$}`,{type:ue.type}),be=new FormData;be.append("file",le);const Te=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:be});if(!Te.ok){const Le=await Te.json().catch(()=>({}));P(Le.error||"Cover import failed.");return}W("present"),Q(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(le)))}catch{P("Cover import failed.")}finally{G(!1)}}},[e,t]),T=w.useCallback(()=>{var K;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.`;(K=navigator.clipboard)==null||K.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 R=O==="present"?"Cover set":O==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",V=O==="present"?"text-green-700":O==="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),de(!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),de(!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),de(!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"}),nl.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=>{y(C.target.value),de(!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"}),Xr.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 ${V}`,"data-testid":"story-info-cover-status",children:R}),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=B.current)==null?void 0:C.click()},disabled:ae,"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:ae?"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:I?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:B,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=>{j(C.target.checked),de(!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:U,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"}),te&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),_e&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:_e})]})]})]})}function OD({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 zD({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var vt,Ve;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[y,N]=w.useState(!1),[j,E]=w.useState(null),[z,O]=w.useState(null),[W,q]=w.useState(null),[D,te]=w.useState(null),[de,_e]=w.useState(null),P=async()=>{try{const Me=await t(`/api/stories/${e}/cover-asset`),Je=Me.ok?await Me.json():null;if(!(Je!=null&&Je.found)||!Je.valid||!Je.path)return null;const It=await t(`/api/stories/${e}/asset/${String(Je.path).replace(/^assets\//,"")}`);if(!It.ok)return null;const Ae=await It.blob();return new File([Ae],String(Je.path).split("/").pop()||"cover.webp",{type:Je.type||Ae.type})}catch{return null}};w.useEffect(()=>{let Me=!1;return(async()=>{v(!0),N(!1);try{const It=await t(`/api/stories/${e}/progress`),Ae=It.ok?await It.json():null;if(Me)return;!Ae||!Array.isArray(Ae.episodes)?(N(!0),x(null)):x(Ae),v(!1)}catch{Me||(N(!0),x(null),v(!1))}})(),()=>{Me=!0}},[e,t,f]);const ae=((Ve=(vt=_==null?void 0:_.episodes)==null?void 0:vt.find(Me=>!Me.published))==null?void 0:Ve.file)??null,G=ae==="genesis.md",Y=JSON.stringify([ae??"",f]),[Q,I]=w.useState(null);if(Q!==Y&&(I(Y),O(null),q(null),te(null),_e(null)),w.useEffect(()=>{if(!ae)return;let Me=!1;const Je=ae.replace(/\.md$/,"");return(async()=>{var It;try{const Ae=[t(`/api/stories/${e}/${ae}`),t(`/api/stories/${e}/cuts/${Je}`)];G&&Ae.push(t(`/api/stories/${e}/structure.md`));const[ii,Ct,pi]=await Promise.all(Ae);if(Me)return;if(O(ii.ok?(await ii.json()).content??"":""),Ct.ok){const ne=await Ct.json();if(Me)return;q(Array.isArray(ne.cuts)?ne.cuts:[]),te(typeof ne.title=="string"?ne.title:null)}else q(null),te(null);_e(G&&pi&&pi.ok?((It=await pi.json())==null?void 0:It.content)??null:null)}catch{Me||(O(""),q(null),te(null),_e(null))}})(),()=>{Me=!0}},[ae,G,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(y||!_)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(Me=>!Me.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 B=A.cuts,U=_.cover==="present",ge=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:B&&B.total>0?"done":"todo",detail:B?`${B.total} cut${B.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:B&&B.needClean>0&&B.withClean===B.needClean?"done":"todo",detail:B?`${B.withClean} / ${B.needClean}`:null},{label:"Cuts lettered",status:B&&B.needClean>0&&B.withText===B.needClean?"done":"todo",detail:B?`${B.withText} / ${B.needClean}`:null},{label:"Final images exported",status:B&&B.total>0&&B.exported===B.total?"done":"todo",detail:B?`${B.exported} / ${B.total}`:null},{label:"Final images uploaded",status:B&&B.total>0&&B.uploaded===B.total?"done":"todo",detail:B?`${B.uploaded} / ${B.total}`:null},{label:"Cover image",status:U?"done":"todo",detail:U?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",R=A.state==="blocked",V=A.file==="genesis.md",C=!V||!!c&&!!h,K=!!o&&o===A.file,re=z!==null,ue=re?bm({fileName:A.file,fileContent:z??"",storySlug:e,structureContent:de,contentType:"cartoon",episodeTitle:D}):null,$=!!ue&&jo(ue,A.file),le=!V&&re&&!_m({fileContent:z??"",episodeTitle:D}),be=$||le,Te=V&&re?mm(z??""):null,Le=!!Te&&Te.blockers.length>0,ze=!V&&re&&W!==null?HS(z??"",W):null,ye=ze&&ze.stage==="error"?ze.issues:[],bt=T&&C&&(re&&(V||W!==null))&&!be&&!Le&&!K&&!!a,wt=async()=>{if(!(!bt||!a)){E(null);try{const Me=V?await P():null;await a(e,A.file,c??"",h??"",!!p,Me)}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((Me,Je)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Me.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Me.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Me.status==="done"?"✓":"○"}),d.jsx("span",{className:Me.status==="done"?"text-foreground":"text-muted",children:Me.label}),Me.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Me.detail]})]},Je))}),ue&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":$?"true":"false","data-blocked":be?"true":"false",children:[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:be?"text-error font-medium":"text-foreground",children:ue})]}),$?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."]}):le?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",ue,"” 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]}),Te&&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."}),Te.blockers.map((Me,Je)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Me},`b-${Je}`)),Te.warnings.map((Me,Je)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Me},`w-${Je}`))]}),ye.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"})]}),US(ye).map(Me=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Me.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Me.title})},Me.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:ye.map((Me,Je)=>d.jsx("li",{className:"font-mono break-words",children:Me},Je))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!U&&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 ",R?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:wt,disabled:!bt,"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:bt?void 0:"Finish the remaining steps above first",children:K?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?be||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:R?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),j&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:j})]}),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 PD(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 ID(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?jo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=PD(i,s);return a?jo(a,t)||Lp(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function HD(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 JS="plotlink-panel-ratio",UD=.6,by=300,Lf=224,Of=6;function $D(){try{const e=localStorage.getItem(JS);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return UD}function vy(e,t){if(t<=0)return e;const i=by/t,s=1-by/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function FD({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(""),[y,N]=w.useState(null),[j,E]=w.useState(null),[z,O]=w.useState($D),[W,q]=w.useState([]),[D,te]=w.useState(!1),[de,_e]=w.useState(""),[P,ae]=w.useState(""),[G,Y]=w.useState(""),[Q,I]=w.useState("English"),[A,B]=w.useState("normal"),[U,ge]=w.useState("claude"),[T,R]=w.useState(null),[V,C]=w.useState(!1),[K,re]=w.useState({}),[ue,$]=w.useState({}),[le,be]=w.useState(new Set),[Te,Le]=w.useState(new Set),[ze,ye]=w.useState({}),[rt,bt]=w.useState({}),[wt,vt]=w.useState({}),[Ve,Me]=w.useState({}),[Je,It]=w.useState({}),[Ae,ii]=w.useState({}),Ct=w.useRef(new Map),pi=w.useRef(new Map),ne=w.useRef(new Map),xe=w.useRef(new Map),Be=w.useRef(new Set),$e=w.useRef(null),Ge=w.useRef(null),Ot=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(ee=>ee.ok?ee.json():null).then(ee=>{ee!=null&&ee.address&&E(ee.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(ee=>ee.ok?ee.json():null).then(ee=>{ee&&R(ee)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(JS,String(z))}catch{}},[z]),w.useEffect(()=>{const ee=()=>{if(!Ge.current)return;const me=Ge.current.getBoundingClientRect().width-Lf-Of;O(Ce=>vy(Ce,me))};return window.addEventListener("resize",ee),ee(),()=>window.removeEventListener("resize",ee)},[]);const Mt=w.useCallback(()=>{_e(""),ae(""),Y(""),B("normal"),ge("claude"),te(!0)},[]),ct=w.useCallback(async(ee,me,Ce,ut)=>{const ot=de.trim();if(!ot)return;const tt=ee==="cartoon"?"codex":ut;try{const st=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:ot,description:P.trim()||void 0,language:me,genre:G||void 0,contentType:ee,agentMode:Ce,agentProvider:tt})});if(!st.ok)return;const it=await st.json();te(!1),ye(kt=>({...kt,[it.name]:ee})),bt(kt=>({...kt,[it.name]:me})),G&&vt(kt=>({...kt,[it.name]:G})),$(kt=>({...kt,[it.name]:tt})),Ce==="bypass"&&re(kt=>({...kt,[it.name]:!0})),s(it.name),o(null)}catch{}},[t,de,P,G]);w.useEffect(()=>{if(W.length===0)return;const ee=setInterval(async()=>{try{const me=await t("/api/stories");if(!me.ok)return;const Ce=await me.json(),ut=new Set(Ce.stories.filter(ot=>ot.name!=="_example").map(ot=>ot.name));for(const ot of ut)if(!Be.current.has(ot)&&W.length>0){const tt=W[0],st=Ct.current.get(tt)||"fiction",it=pi.current.get(tt)||"English",kt=ne.current.get(tt)||"normal",ht=xe.current.get(tt)||"claude";let Kt=!1;$e.current&&(Kt=await $e.current(tt,ot,{contentType:st,language:it,agentMode:kt,agentProvider:ht}).catch(()=>!1)),Kt&&(q(Lt=>Lt.slice(1)),Ct.current.delete(tt),pi.current.delete(tt),ne.current.delete(tt),xe.current.delete(tt),kt==="bypass"&&re(Lt=>{const oi={...Lt,[ot]:!0};return delete oi[tt],oi}),$(Lt=>{const oi={...Lt,[ot]:ht};return delete oi[tt],oi}),t(`/api/stories/${ot}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:st,language:it,agentMode:kt,agentProvider:ht})}).catch(()=>{})),s(ot),o(null)}Be.current=ut}catch{}},3e3);return()=>clearInterval(ee)},[t,W]),w.useEffect(()=>{t("/api/stories").then(ee=>{if(ee.ok)return ee.json()}).then(ee=>{ee!=null&&ee.stories&&(Be.current=new Set(ee.stories.filter(me=>me.name!=="_example").map(me=>me.name)))}).catch(()=>{})},[t]);const We=w.useCallback((ee,me)=>{s(ee),o(me),h(null)},[]),Bt=w.useRef(null),pt=w.useCallback(async ee=>{var me,Ce,ut,ot;Bt.current=ee,s(ee),o(null),h(null);try{const tt=await t(`/api/stories/${ee}`);if(tt.ok&&Bt.current===ee){const st=await tt.json();if(st.contentType==="cartoon")return;const it=st.files||[],ht=((me=it.map(Kt=>{var Lt;return{file:Kt.file,num:(Lt=Kt.file.match(/^plot-(\d+)\.md$/))==null?void 0:Lt[1]}}).filter(Kt=>Kt.num!=null).sort((Kt,Lt)=>parseInt(Lt.num)-parseInt(Kt.num))[0])==null?void 0:me.file)??((Ce=it.find(Kt=>Kt.file==="genesis.md"))==null?void 0:Ce.file)??((ut=it.find(Kt=>Kt.file==="structure.md"))==null?void 0:ut.file)??((ot=it[0])==null?void 0:ot.file);ht&&Bt.current===ee&&o(ht)}}catch{}},[t]),Mi=w.useCallback(ee=>{ee.preventDefault(),Ot.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const me=ut=>{if(!Ot.current||!Ge.current)return;const ot=Ge.current.getBoundingClientRect(),tt=ot.width-Lf-Of,st=ut.clientX-ot.left-Lf;O(vy(st/tt,tt))},Ce=()=>{Ot.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",Ce)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",Ce)},[]),H=w.useCallback(async(ee,me,Ce,ut,ot,tt)=>{var ht;f(me),v("Reading file..."),N(null);let st=!1,it=null,kt=!1;try{const Kt=await t(`/api/stories/${ee}/${me}`);if(!Kt.ok)throw new Error("Failed to read file");const Lt=await Kt.json(),oi=ze[ee];let Fi=null,Fn=null;if(me==="genesis.md")try{const Vt=await t(`/api/stories/${ee}/structure.md`);Vt.ok&&(Fi=(await Vt.json()).content??null)}catch{}else if(oi==="cartoon"&&me.match(/^plot-\d+\.md$/))try{const Vt=await t(`/api/stories/${ee}/cuts/${me.replace(/\.md$/,"")}`);Vt.ok&&(Fn=(await Vt.json()).title??null)}catch{}const qi=bm({fileName:me,fileContent:Lt.content,storySlug:ee,structureContent:Fi,contentType:oi,episodeTitle:Fn});if(oi==="cartoon"&&jo(qi,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(oi==="cartoon"&&me.match(/^plot-\d+\.md$/)&&!_m({fileContent:Lt.content,episodeTitle:Fn}))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(oi==="cartoon"&&me==="genesis.md"){const Vt=mm(Lt.content).blockers;if(Vt.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${Vt[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let ni;if(me.match(/^plot-\d+\.md$/)){if(cD(Lt)){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 Vt=await t(`/api/stories/${ee}`);if(Vt.ok){const ln=(await Vt.json()).files.find(An=>An.file==="genesis.md"&&An.storylineId);ni=ln==null?void 0:ln.storylineId}}catch{}if(!ni)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const Vt=await t("/api/publish/preflight");if(Vt.ok){const Wn=await Vt.json();if(hD(Wn))return N(dD(Wn)),f(null),v(""),!1}}catch{}v("Publishing...");const jn=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:ee,fileName:me,title:qi,content:Lt.content,genre:Ce,language:ut,isNsfw:ot,storylineId:ni,...my(ze,ee,ni)?{contentType:my(ze,ee,ni)}:{}})});if(!jn.ok){const Vt=await jn.json();throw new Error(Vt.error||"Publish failed")}const qn=(ht=jn.body)==null?void 0:ht.getReader(),ri=new TextDecoder;if(qn)for(;;){const{done:Vt,value:Wn}=await qn.read();if(Vt)break;const An=ri.decode(Wn).split(` +`).filter(ts=>ts.startsWith("data: "));for(const ts of An)try{const Jt=JSON.parse(ts.slice(6));if(Jt.step&&v(Jt.message||Jt.step),Jt.step==="done"&&Jt.txHash){if(kt=!0,await t(`/api/stories/${ee}/${me}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Jt.txHash,storylineId:Jt.storylineId,plotIndex:Jt.plotIndex,contentCid:Jt.contentCid,gasCost:Jt.gasCost,indexError:Jt.indexError,authorAddress:j})}),x(xn=>xn+1),tt&&me==="genesis.md"&&Jt.storylineId){v("Uploading cover...");let xn=null;try{xn=await sD(t,Jt.storylineId,tt)}catch{}xn||(st=!0)}if(oi==="cartoon"&&Jt.storylineId)try{const xn=me!=="genesis.md",dl=`storylineId=${Jt.storylineId}`+(xn&&Jt.plotIndex!=null?`&plotIndex=${Jt.plotIndex}`:""),Ar=await t(`/api/publish/public-title?${dl}`);if(Ar.ok){const or=await Ar.json(),_n=xn?{plots:or.plotTitle!=null?[{plotIndex:Jt.plotIndex,title:or.plotTitle}]:[]}:{title:or.storylineTitle},Qi=ID({fileName:me,detail:_n,plotIndex:Jt.plotIndex});Qi.ok||(it=HD(Qi))}}catch{}}}catch{}}it&&N(it),v(st?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Kt){const Lt=Kt instanceof Error?Kt.message:"Publish failed";v(`Error: ${Lt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return kt&&!st},[t,ze,j]),ke=w.useCallback(ee=>{ee.startsWith("_new_")&&(q(me=>me.filter(Ce=>Ce!==ee)),Ct.current.delete(ee),pi.current.delete(ee),ne.current.delete(ee),xe.current.delete(ee),re(me=>{if(!(ee in me))return me;const Ce={...me};return delete Ce[ee],Ce}),$(me=>{if(!(ee in me))return me;const Ce={...me};return delete Ce[ee],Ce}))},[]);w.useEffect(()=>{const ee=Ce=>{be(new Set(Ce.filter(ht=>ht.hasStructure).map(ht=>ht.name))),Le(new Set(Ce.filter(ht=>ht.hasGenesis).map(ht=>ht.name)));const ut={},ot={},tt={},st={},it={},kt={};for(const ht of Ce)ut[ht.name]=ht.contentType||"fiction",ot[ht.name]=ht.language,tt[ht.name]=ht.genre,st[ht.name]=ht.isNsfw,it[ht.name]=ht.agentProvider,ht.title&&(kt[ht.name]=ht.title);ye(ut),bt(ot),vt(tt),Me(st),ii(it),It(kt)};t("/api/stories").then(Ce=>Ce.ok?Ce.json():null).then(Ce=>{Ce!=null&&Ce.stories&&ee(Ce.stories)}).catch(()=>{});const me=setInterval(async()=>{try{const Ce=await t("/api/stories");if(Ce.ok){const ut=await Ce.json();ee(ut.stories)}}catch{}},5e3);return()=>clearInterval(me)},[t]);const Pe=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",je=!!T&&!Pe,Ie=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Xe=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const ee=i;if((await t(`/api/stories/${ee}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ii(Ce=>({...Ce,[ee]:"codex"})),$(Ce=>({...Ce,[ee]:"codex"}));try{const Ce=await t("/api/stories");if(Ce.ok){const ut=await Ce.json();if(ut!=null&&ut.stories){const ot={};for(const tt of ut.stories)ot[tt.name]=tt.agentProvider;ii(ot)}}}catch{}}},[t,i]),mt=w.useCallback(ee=>{i===ee&&(s(null),o(null))},[i]),Qe=i?ue[i]??Ae[i]:void 0,Tt=Mf(i,ze,Ct.current),qt=uD(Tt,Qe,i),li=!!i&&Tt==="cartoon",oe=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",Ee=w.useCallback(ee=>{const me=i;if(me)switch(ee){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":We(me,"structure.md");break;case"genesis":We(me,"genesis.md");break;case"publish":h("publish");break}},[i,We]),Ue=w.useCallback((ee,me)=>{const Ce=i;if(Ce)switch(ee){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":me&&We(Ce,me);break}},[i,We]),Ye=w.useCallback(ee=>{i&&(ee.genre!==void 0&&vt(me=>({...me,[i]:ee.genre||void 0})),ee.language!==void 0&&bt(me=>({...me,[i]:ee.language||void 0})),ee.isNsfw!==void 0&&Me(me=>({...me,[i]:ee.isNsfw})))},[i]);return d.jsxs("div",{ref:Ge,className:"h-[calc(100vh-3.5rem)] flex",children:[d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(yC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:We,onNewStory:Mt,untitledSessions:W})}),d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${z} 0 0`},children:d.jsx(YE,{token:e,storyName:i,authFetch:t,onSelectStory:pt,onDestroySession:ke,onArchiveStory:mt,confirmedStories:le,renameRef:$e,bypassStories:K,agentProviders:ue,readiness:T,contentType:Mf(i,ze,Ct.current),needsProviderRepair:qt,onRepairProvider:Xe})}),d.jsx("div",{onMouseDown:Mi,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Of,cursor:"col-resize",background:"var(--border)"},children: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 flex flex-col",style:{flex:`${1-z} 0 0`},children:[li&&i&&d.jsx(BD,{storyTitle:Je[i]||i,active:oe,onSelect:Ee}),li&&i&&c!==null&&d.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:d.jsx(vD,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:Ue,onOpenStoryInfo:()=>h("story-info")})}),li&&c==="story-info"&&i?d.jsx(LD,{storyName:i,authFetch:t,onSaved:Ye}):li&&c==="episodes"&&i?d.jsx(OD,{storyName:i,authFetch:t,onOpenFile:We}):li&&c==="publish"&&i?d.jsx(zD,{storyName:i,authFetch:t,onOpenFile:We,onOpenStoryInfo:()=>h("story-info"),onPublish:H,publishingFile:p,genre:wt[i],language:rt[i],isNsfw:Ve[i],refreshKey:_}):i&&!a?d.jsx(SD,{storyName:i,authFetch:t,onOpenFile:We,onOpenStoryInfo:()=>h("story-info")}):d.jsx(xD,{storyName:i,fileName:a,authFetch:t,onPublish:H,publishingFile:p,walletAddress:j,contentType:Mf(i,ze,Ct.current)||"fiction",language:i?rt[i]:void 0,genre:i?wt[i]:void 0,isNsfw:i?Ve[i]:void 0,hasGenesis:i?Te.has(i):!1,onViewProgress:()=>o(null),onOpenFile:ee=>i&&We(i,ee),onViewPublish:()=>h("publish")}),b&&d.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),y&&d.jsxs("div",{className:"px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[d.jsx("span",{children:y}),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"})]})]}),D&&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:de,onChange:ee=>_e(ee.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:P,onChange:ee=>ae(ee.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:G,onChange:ee=>Y(ee.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 —"}),nl.map(ee=>d.jsx("option",{value:ee,children:ee},ee))]})]}),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:Q,onChange:ee=>I(ee.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:Xr.map(ee=>d.jsx("option",{value:ee,children:ee},ee))})]}),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:ee=>B(ee.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:U,onChange:ee=>ge(ee.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:U==="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"}),!de.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:()=>ct("fiction",Q,A,U),disabled:!de.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:()=>ct("cartoon",Q,A,"codex"),disabled:je||!de.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."]}),Su(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:zp}),T&&T.codex.installed&&!Su(T)&&T.codex.imageGeneration!=="enabled"&&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:Ie,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:()=>te(!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 qD({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 WD({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(y=>y.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(Cy,{token:e})]}),i==="stories"&&d.jsx(FD,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(_C,{token:e}),i==="wallet-setup"&&d.jsx(qD,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(gC,{token:e,onLogout:t})]})]})}function GD(){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(WD,{token:e,onLogout:p}):d.jsx(pC,{onLogin:c}):d.jsx(mC,{onSetup:h})}fC.createRoot(document.getElementById("root")).render(d.jsx(sC.StrictMode,{children:d.jsx(GD,{})}));export{Dp as M,su as a,j3 as b,OM as c,R3 as d,ru as l,OS as s,F3 as t,ZD as v}; diff --git a/app/web/dist/assets/index-DP8e99_8.css b/app/web/dist/assets/index-SgqE3Vv0.css similarity index 56% rename from app/web/dist/assets/index-DP8e99_8.css rename to app/web/dist/assets/index-SgqE3Vv0.css index b9de878..ee029e3 100644 --- a/app/web/dist/assets/index-DP8e99_8.css +++ b/app/web/dist/assets/index-SgqE3Vv0.css @@ -29,4 +29,4 @@ * The original design remains. The terminal itself * has been extended to include xterm CSI codes, among * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:calc(var(--spacing) * 44)}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-52{width:calc(var(--spacing) * 52)}.w-56{width:calc(var(--spacing) * 56)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false} + */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:calc(var(--spacing) * 44)}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-\[32rem\]{max-height:32rem}.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-52{width:calc(var(--spacing) * 52)}.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-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 2c67e3b..0449b07 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,8 +7,8 @@ - - + +
From d894966056cb4478533d6d1b5e89a73b694fe8b9 Mon Sep 17 00:00:00 2001 From: Project7 Date: Sun, 7 Jun 2026 08:56:51 +0000 Subject: [PATCH 2/2] Gate lettering progress on text panels --- app/lib/cartoon-coach.test.ts | 16 +++++-- app/lib/cartoon-coach.ts | 2 +- app/lib/cartoon-readiness.test.ts | 24 ++++++++-- app/lib/cartoon-readiness.ts | 22 +++++----- app/lib/story-progress.ts | 5 +-- app/web/components/CartoonPublishPage.tsx | 2 +- app/web/components/PreviewPanel.tsx | 2 +- ...cut-BdY0Az65.js => export-cut-che5mMWc.js} | 2 +- ...{index-SgqE3Vv0.css => index-CcfChGEK.css} | 2 +- .../{index-Mt6kwRka.js => index-Dc2TQ3Ij.js} | 44 +++++++++---------- app/web/dist/index.html | 4 +- 11 files changed, 75 insertions(+), 50 deletions(-) rename app/web/dist/assets/{export-cut-BdY0Az65.js => export-cut-che5mMWc.js} (98%) rename app/web/dist/assets/{index-SgqE3Vv0.css => index-CcfChGEK.css} (55%) rename app/web/dist/assets/{index-Mt6kwRka.js => index-Dc2TQ3Ij.js} (93%) diff --git a/app/lib/cartoon-coach.test.ts b/app/lib/cartoon-coach.test.ts index 3fce3d7..5861bbb 100644 --- a/app/lib/cartoon-coach.test.ts +++ b/app/lib/cartoon-coach.test.ts @@ -125,12 +125,20 @@ describe("deriveCartoonCoach (#429)", () => { expect(c.stageLabel).toBe("Ready to publish"); }); - it("text panels never gate the clean/letter stage (#350)", () => { - // One bare text panel: needClean === 0, so the coach skips the clean and - // lettering stages and goes straight to exporting the panel's final image. + it("text panels skip clean but still gate the letter stage (#350/#488)", () => { + // One bare text panel: needClean === 0, so the coach skips clean images, but + // still keeps the creator in the focused lettering workflow before export. const c = deriveCartoonCoach(cartoon([ep({ file: "plot-01.md", cuts: [textPanel(1)] })]))!; expect(c.uiAction).toBe("open-lettering"); - expect(c.action).toMatch(/export/i); + expect(c.action).toMatch(/lettering/i); + expect(c.stageLabel).toBe("Clean images ready"); + }); + + it("empty text panels keep the coach at lettering after image cuts are lettered (#488 re2)", () => { + const c = deriveCartoonCoach(cartoon([ep({ file: "plot-01.md", cuts: [lettered(1), textPanel(2)] })]))!; + expect(c.uiAction).toBe("open-lettering"); + expect(c.action).toMatch(/lettering/i); + expect(c.action).not.toMatch(/export/i); }); it("focus on an unfinished episode overrides the story's active episode", () => { diff --git a/app/lib/cartoon-coach.ts b/app/lib/cartoon-coach.ts index 8b1743b..61be8ed 100644 --- a/app/lib/cartoon-coach.ts +++ b/app/lib/cartoon-coach.ts @@ -168,7 +168,7 @@ function coachForEpisode(ep: EpisodeProgress, undetectedClean: number): CartoonC } // 2) Lettering — place speech bubbles & captions in the cut workspace. - if (c.withText < c.needClean) { + if (c.withText < c.total) { return ui("Clean images ready", "Review cuts and start lettering", "open-lettering", file); } diff --git a/app/lib/cartoon-readiness.test.ts b/app/lib/cartoon-readiness.test.ts index 4d468c9..da61229 100644 --- a/app/lib/cartoon-readiness.test.ts +++ b/app/lib/cartoon-readiness.test.ts @@ -592,6 +592,7 @@ describe("text panels (#350)", () => { expect(p.total).toBe(2); expect(p.needClean).toBe(1); // only the image cut expect(p.withClean).toBe(1); + expect(p.withText).toBe(1); // the image cut is lettered; the empty text panel is not expect(p.exported).toBe(2); // both panels exported expect(p.uploaded).toBe(2); }); @@ -610,14 +611,15 @@ describe("text panels (#350)", () => { expect(checkCartoonReadiness(cuts).ready).toBe(true); }); - it("cartoonChecklist: an all-text episode skips clean/letter and points at export", () => { + it("cartoonChecklist: an all-text episode skips clean but still requires text-card lettering", () => { const r = cartoonChecklist({ cuts: [makeCut({ id: 1, kind: "text" })] }); const statusOf = (k: string) => r.steps.find((s) => s.key === k)!.status; expect(statusOf("clean")).toBe("done"); // no image cuts to clean - expect(statusOf("letter")).toBe("done"); - expect(statusOf("export")).toBe("current"); + expect(statusOf("letter")).toBe("current"); + expect(statusOf("export")).toBe("todo"); expect(r.steps.find((s) => s.key === "clean")!.detail).toBe("no image cuts"); - expect(r.nextStep).toMatch(/export/i); + expect(r.steps.find((s) => s.key === "letter")!.detail).toBe("0 / 1 cut"); + expect(r.nextStep).toMatch(/lettering editor|speech bubbles/i); }); it("cartoonChecklist: a mixed plan still gates clean on the image cut", () => { @@ -627,6 +629,20 @@ describe("text panels (#350)", () => { expect(statusOf("clean")).toBe("current"); expect(r.steps.find((s) => s.key === "clean")!.detail).toBe("0 / 1 cut"); }); + + it("cartoonChecklist: an empty text panel keeps lettering current even after image cuts are lettered (#488 re2)", () => { + const cuts = [ + makeCut(imageDone(1)), + makeCut({ id: 2, kind: "text", overlays: [] }), + ]; + const r = cartoonChecklist({ cuts }); + const statusOf = (k: string) => r.steps.find((s) => s.key === k)!.status; + expect(statusOf("clean")).toBe("done"); + expect(statusOf("letter")).toBe("current"); + expect(statusOf("export")).toBe("todo"); + expect(r.steps.find((s) => s.key === "letter")!.detail).toBe("1 / 2 cuts"); + expect(r.nextStep).toMatch(/lettering editor|speech bubbles/i); + }); }); describe("cartoonGenesisReadiness (#359, hardened in #400)", () => { diff --git a/app/lib/cartoon-readiness.ts b/app/lib/cartoon-readiness.ts index 7ed5850..3104a6f 100644 --- a/app/lib/cartoon-readiness.ts +++ b/app/lib/cartoon-readiness.ts @@ -492,7 +492,7 @@ export interface CartoonCutProgress { needClean: number; /** Of `needClean`, how many have a clean image recorded. */ withClean: number; - /** Of the clean-image cuts, how many have text overlays placed. */ + /** Cuts with lettering overlays placed. Image cuts still require clean art first; text panels are first-class lettering targets. */ withText: number; /** Cuts (any kind) with an exported final image. */ exported: number; @@ -517,8 +517,8 @@ export function summarizeCutProgress(cuts: Cut[]): CartoonCutProgress { let uploaded = 0; for (const cut of cuts) { // Image cuts need a clean image → lettering; text/interstitial panels (#350) - // do not (they're text on a styled background). Every panel still exports + - // uploads a final image, so those are counted for both kinds. + // do not (they're text on a styled background). Text panels still require + // lettering overlays before the shared workflow can advance to export (#488). if (!isTextPanel(cut)) { needClean++; // A PNG clean image is a draft intermediate, not a finished clean asset @@ -531,6 +531,8 @@ export function summarizeCutProgress(cuts: Cut[]): CartoonCutProgress { // every cut-list render now (#414), so a bad persisted cut must not crash it. if ((cut.overlays?.length ?? 0) > 0) withText++; } + } else if ((cut.overlays?.length ?? 0) > 0) { + withText++; } if (cut.finalImagePath && cut.exportedAt) exported++; if (cut.uploadedUrl) uploaded++; @@ -583,12 +585,12 @@ export function cartoonChecklist(input: { cuts: Cut[]; published?: boolean }): C const p = summarizeCutProgress(cuts); if (p.total === 0) return { steps: [], nextStep: null }; - // Clean + letter gate only IMAGE cuts (needClean); export + upload gate EVERY - // cut including text panels (total). For an all-image story needClean === total - // so this is unchanged from before (#350). + // Clean gates only IMAGE cuts (needClean); lettering/export/upload gate EVERY + // cut including text panels. Text panels need no clean art, but they are still + // editable lettering targets before export (#488). const planDone = p.total > 0; const cleanDone = planDone && p.withClean === p.needClean; - const letterDone = cleanDone && p.withText === p.needClean; + const letterDone = cleanDone && p.withText === p.total; const exportDone = letterDone && p.exported === p.total; const uploadDone = exportDone && p.uploaded === p.total; const publishDone = uploadDone && published; @@ -604,13 +606,13 @@ export function cartoonChecklist(input: { cuts: Cut[]; published?: boolean }): C const order: CartoonStepKey[] = ["plan", "clean", "letter", "export", "upload", "publish"]; const currentIdx = order.findIndex((k) => !complete[k]); - // Clean/letter count image cuts (needClean); export/upload count every cut + // Clean counts image cuts (needClean); lettering/export/upload count every cut // (total). An all-text-panel episode has needClean === 0 → "no image cuts". const imageDetail = (done: number) => (p.needClean > 0 ? fraction(done, p.needClean) : "no image cuts"); const detail: Record = { plan: fraction(p.total, p.total), clean: imageDetail(p.withClean), - letter: imageDetail(p.withText), + letter: fraction(p.withText, p.total), export: fraction(p.exported, p.total), upload: fraction(p.uploaded, p.total), publish: null, @@ -702,7 +704,7 @@ export function previewFooterGuidance(ctx: PreviewFooterContext): string | null if (p.withClean < p.needClean) { return "Genesis has a cut plan — generate the clean images for its cuts next."; } - if (p.withText < p.needClean) { + if (p.withText < p.total) { return "Genesis clean art is ready — review the cuts and add speech bubbles & captions next."; } if (p.exported < p.total) { diff --git a/app/lib/story-progress.ts b/app/lib/story-progress.ts index 6531af9..6aea998 100644 --- a/app/lib/story-progress.ts +++ b/app/lib/story-progress.ts @@ -38,9 +38,8 @@ export interface EpisodeProgress { summary: string; published: boolean; /** - * Cartoon cut progress; null for fiction. `needClean`/`withText` count IMAGE - * cuts only (text panels are excluded), so the workflow coach (#429) can tell - * the clean-image stage from the lettering stage. + * Cartoon cut progress; null for fiction. `needClean`/`withClean` count image + * cuts only; `withText`, export, and upload count every cut including text panels. */ cuts: { total: number; needClean: number; withClean: number; withText: number; exported: number; uploaded: number } | null; /** diff --git a/app/web/components/CartoonPublishPage.tsx b/app/web/components/CartoonPublishPage.tsx index 22f9c2f..0ce8f43 100644 --- a/app/web/components/CartoonPublishPage.tsx +++ b/app/web/components/CartoonPublishPage.tsx @@ -178,7 +178,7 @@ export function CartoonPublishPage({ storyName, authFetch, onOpenFile, onOpenSto { label: "Opening text ready", status: "done" }, // the episode exists once it appears here { label: "Cut plan", status: c && c.total > 0 ? "done" : "todo", detail: c ? `${c.total} cut${c.total === 1 ? "" : "s"} planned` : "not started" }, { label: "Clean images converted", status: c && c.needClean > 0 && c.withClean === c.needClean ? "done" : "todo", detail: c ? `${c.withClean} / ${c.needClean}` : null }, - { label: "Cuts lettered", status: c && c.needClean > 0 && c.withText === c.needClean ? "done" : "todo", detail: c ? `${c.withText} / ${c.needClean}` : null }, + { label: "Cuts lettered", status: c && c.total > 0 && c.withText === c.total ? "done" : "todo", detail: c ? `${c.withText} / ${c.total}` : null }, { label: "Final images exported", status: c && c.total > 0 && c.exported === c.total ? "done" : "todo", detail: c ? `${c.exported} / ${c.total}` : null }, { label: "Final images uploaded", status: c && c.total > 0 && c.uploaded === c.total ? "done" : "todo", detail: c ? `${c.uploaded} / ${c.total}` : null }, { label: "Cover image", status: coverDone ? "done" : "todo", detail: coverDone ? null : "recommended before publishing" }, diff --git a/app/web/components/PreviewPanel.tsx b/app/web/components/PreviewPanel.tsx index 2d7a7ac..b9e35d0 100644 --- a/app/web/components/PreviewPanel.tsx +++ b/app/web/components/PreviewPanel.tsx @@ -1335,7 +1335,7 @@ export function PreviewPanel({ storyName, fileName, authFetch, onPublish, publis
Cuts: {cartoonCutProgress.total} Clean: {cartoonCutProgress.withClean}/{cartoonCutProgress.needClean} - Lettered: {cartoonCutProgress.withText}/{cartoonCutProgress.needClean} + Lettered: {cartoonCutProgress.withText}/{cartoonCutProgress.total} Uploaded: {cartoonCutProgress.uploaded}/{cartoonCutProgress.total} {onViewProgress && (